uiport 0.0.0-bootstrap.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,265 @@
1
+ // @ts-check
2
+ import fs from "node:fs/promises";
3
+ import path from "node:path";
4
+ import postcss from "postcss";
5
+ import valueParser from "postcss-value-parser";
6
+ import {
7
+ extensionFor,
8
+ normalizeUrl,
9
+ sha256,
10
+ redactedUrl,
11
+ safeErrorMessage,
12
+ limitation,
13
+ } from "./lib.mjs";
14
+
15
+ /** @param {string} directory @param {import('./options.mjs').optionsFor extends (...args: any[]) => infer T ? T : never} options @param {AbortSignal} signal @param {{code:string,message:string}[]} limitations @param {{get:(url:string)=>Promise<any>} | undefined} [browserCache] */
16
+ export function resources(
17
+ directory,
18
+ options,
19
+ signal,
20
+ limitations,
21
+ browserCache,
22
+ ) {
23
+ const downloaded = new Map();
24
+ let consumed = 0;
25
+ const localPaths = new Set();
26
+ /** @param {string} input */
27
+ async function download(input) {
28
+ const url = normalizeUrl(input);
29
+ if (downloaded.has(url)) return downloaded.get(url);
30
+ if (!/^https?:/i.test(url)) return null;
31
+ let response;
32
+ try {
33
+ if (consumed >= options.maxTotalBytes)
34
+ throw new Error("Total resource budget exceeded");
35
+ const cached = await browserCache?.get(url);
36
+ if (cached) {
37
+ if (
38
+ cached.body.length > options.maxResourceBytes ||
39
+ consumed + cached.body.length > options.maxTotalBytes
40
+ )
41
+ throw new Error("Resource size limit exceeded");
42
+ consumed += cached.body.length;
43
+ downloaded.set(url, cached);
44
+ return cached;
45
+ }
46
+ response = await fetch(url, {
47
+ signal: AbortSignal.any([
48
+ signal,
49
+ AbortSignal.timeout(Math.min(options.timeoutMs, 15000)),
50
+ ]),
51
+ headers: { "user-agent": "UIport/0.1" },
52
+ });
53
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
54
+ const length = Number(response.headers.get("content-length") || 0);
55
+ if (
56
+ length > options.maxResourceBytes ||
57
+ length + consumed > options.maxTotalBytes
58
+ )
59
+ throw new Error("Resource size limit exceeded");
60
+ const chunks = [];
61
+ let size = 0;
62
+ for await (const chunk of /** @type {any} */ (response.body)) {
63
+ size += chunk.length;
64
+ consumed += chunk.length;
65
+ if (size > options.maxResourceBytes || consumed > options.maxTotalBytes)
66
+ throw new Error("Resource size limit exceeded");
67
+ chunks.push(chunk);
68
+ }
69
+ const resource = {
70
+ body: Buffer.concat(chunks),
71
+ contentType: response.headers.get("content-type") || "",
72
+ url: response.url || url,
73
+ };
74
+ downloaded.set(url, resource);
75
+ return resource;
76
+ } catch (error) {
77
+ signal.throwIfAborted();
78
+ limitation(
79
+ limitations,
80
+ "RESOURCE_UNAVAILABLE",
81
+ `${redactedUrl(url)}: ${safeErrorMessage(error)}`,
82
+ );
83
+ downloaded.set(url, null);
84
+ return null;
85
+ } finally {
86
+ if (response?.body && !response.body.locked)
87
+ await response.body.cancel().catch(() => {});
88
+ }
89
+ }
90
+ /** @param {string} raw @param {string} base @param {string} [usage] */
91
+ async function localize(raw, base, usage) {
92
+ if (
93
+ !raw ||
94
+ /^(data:|#)/i.test(raw) ||
95
+ localPaths.has(raw.split("#")[0].replace(/^\.\//, ""))
96
+ )
97
+ return raw;
98
+ let url;
99
+ try {
100
+ url = new URL(raw, base);
101
+ } catch {
102
+ limitation(
103
+ limitations,
104
+ "INVALID_RESOURCE_URL",
105
+ "A resource URL could not be resolved",
106
+ );
107
+ return raw;
108
+ }
109
+ if (!["http:", "https:"].includes(url.protocol)) {
110
+ limitation(
111
+ limitations,
112
+ "RESOURCE_UNAVAILABLE",
113
+ `Unsupported resource protocol: ${url.protocol}`,
114
+ );
115
+ return raw;
116
+ }
117
+ const resource = await download(url.href);
118
+ if (!resource) return url.href;
119
+ let extension = extensionFor(resource.url, resource.contentType);
120
+ if (
121
+ extension === ".bin" &&
122
+ (usage === "script" || resource.resourceType === "script")
123
+ )
124
+ extension = ".js";
125
+ const file = `assets/${sha256(resource.body).slice(0, 24)}${extension}`;
126
+ if (!localPaths.has(file)) {
127
+ await fs.writeFile(path.join(directory, file), resource.body);
128
+ localPaths.add(file);
129
+ }
130
+ return `./${file}${url.hash}`;
131
+ }
132
+ /** @param {string} value @param {string} base */
133
+ async function cssValue(value, base) {
134
+ const parsed = valueParser(value);
135
+ const nodes = [];
136
+ parsed.walk((node) => {
137
+ if (node.type === "function" && node.value.toLowerCase() === "url") {
138
+ nodes.push(node);
139
+ return false;
140
+ }
141
+ if (
142
+ node.type === "function" &&
143
+ ["image-set", "-webkit-image-set"].includes(node.value.toLowerCase())
144
+ ) {
145
+ // Only direct string candidates are URLs. Strings nested in type()
146
+ // describe MIME types and must remain untouched.
147
+ for (const candidate of node.nodes)
148
+ if (candidate.type === "string") nodes.push(candidate);
149
+ }
150
+ });
151
+ for (const node of nodes) {
152
+ const raw =
153
+ node.type === "string" ? node.value : node.nodes[0]?.value || "";
154
+ const localized = await localize(raw, base);
155
+ if (node.type === "string")
156
+ node.value = localized.replaceAll(
157
+ node.quote,
158
+ node.quote === '"' ? "%22" : "%27",
159
+ );
160
+ else
161
+ node.nodes = [
162
+ {
163
+ type: "string",
164
+ quote: '"',
165
+ value: localized.replaceAll('"', "%22"),
166
+ },
167
+ ];
168
+ }
169
+ return parsed.toString();
170
+ }
171
+ /** @param {string} text @param {string} base @param {Set<string>} [stack] */
172
+ async function css(text, base, stack = new Set()) {
173
+ const root = postcss.parse(text, { from: undefined });
174
+ const declarations = [];
175
+ root.walkDecls((decl) => {
176
+ declarations.push(decl);
177
+ });
178
+ const imports = [];
179
+ root.walkAtRules(/^import$/i, (rule) => {
180
+ imports.push(rule);
181
+ });
182
+ for (const rule of imports) {
183
+ const parsed = valueParser(rule.params);
184
+ const first = parsed.nodes.find(
185
+ (n) => n.type !== "space" && n.type !== "comment",
186
+ );
187
+ const raw =
188
+ first?.type === "string"
189
+ ? first.value
190
+ : first?.type === "function" && first.value === "url"
191
+ ? first.nodes[0]?.value
192
+ : null;
193
+ if (!raw) {
194
+ limitation(
195
+ limitations,
196
+ "CSS_IMPORT_UNSUPPORTED",
197
+ "An import could not be parsed",
198
+ );
199
+ continue;
200
+ }
201
+ const url = new URL(raw, base).href;
202
+ if (stack.has(url) || stack.size >= 16) {
203
+ rule.remove();
204
+ limitation(
205
+ limitations,
206
+ "CSS_IMPORT_CYCLE",
207
+ "Circular or excessively nested stylesheet import omitted",
208
+ );
209
+ continue;
210
+ }
211
+ const imported = await download(url);
212
+ if (!imported) {
213
+ rule.params = `url(${JSON.stringify(url)}) ${valueParser.stringify(parsed.nodes.slice(parsed.nodes.indexOf(first) + 1))}`;
214
+ continue;
215
+ }
216
+ let body = await css(
217
+ imported.body.toString("utf8"),
218
+ imported.url,
219
+ new Set([...stack, url]),
220
+ );
221
+ const tail = parsed.nodes
222
+ .slice(parsed.nodes.indexOf(first) + 1)
223
+ .filter((n) => n.type !== "space" && n.type !== "comment");
224
+ const wrappers = [];
225
+ if (tail[0]?.value === "layer") {
226
+ const layer = tail.shift();
227
+ wrappers.push([
228
+ "layer",
229
+ layer.type === "function" ? valueParser.stringify(layer.nodes) : "",
230
+ ]);
231
+ }
232
+ if (tail[0]?.type === "function" && tail[0].value === "supports") {
233
+ const supports = tail[0];
234
+ tail.shift();
235
+ const v = valueParser.stringify(supports.nodes);
236
+ wrappers.push([
237
+ "supports",
238
+ v.includes(":") && !v.trim().startsWith("(") ? `(${v})` : v,
239
+ ]);
240
+ }
241
+ const media = tail.map((n) => valueParser.stringify(n)).join(" ");
242
+ if (media) wrappers.push(["media", media]);
243
+ for (const [name, params] of wrappers.reverse())
244
+ body = `@${name} ${params} {\n${body}\n}`;
245
+ rule.replaceWith(postcss.parse(body).nodes);
246
+ }
247
+ // Imported declarations have already been rewritten against their own base.
248
+ for (const decl of declarations)
249
+ decl.value = await cssValue(decl.value, base);
250
+ root.walkComments((comment) => {
251
+ if (/sourceMappingURL/.test(comment.text)) comment.remove();
252
+ });
253
+ root.walkAtRules(/^charset$/i, (rule) => {
254
+ rule.remove();
255
+ });
256
+ return root.toString();
257
+ }
258
+ return {
259
+ download,
260
+ localize,
261
+ css,
262
+ cssValue,
263
+ stats: () => ({ assets: localPaths.size, downloadedBytes: consumed }),
264
+ };
265
+ }
@@ -0,0 +1,26 @@
1
+ import { startStaticServer } from "./lib.mjs";
2
+ export async function serve(options) {
3
+ const server = await startStaticServer(options.directory, options.port);
4
+ const ready = {
5
+ command: "serve",
6
+ status: "ready",
7
+ directory: options.directory,
8
+ url: server.url,
9
+ };
10
+ console.log(
11
+ options.json
12
+ ? JSON.stringify(ready)
13
+ : `UIport serving ${server.url}\nPress Ctrl+C to stop.`,
14
+ );
15
+ await new Promise((resolve) => {
16
+ const stop = async () => {
17
+ process.removeListener("SIGINT", stop);
18
+ process.removeListener("SIGTERM", stop);
19
+ await server.close();
20
+ resolve();
21
+ };
22
+ process.once("SIGINT", stop);
23
+ process.once("SIGTERM", stop);
24
+ });
25
+ return { command: "serve", status: "stopped" };
26
+ }
@@ -0,0 +1,212 @@
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+ import pixelmatch from "pixelmatch";
4
+ import { PNG } from "pngjs";
5
+ import { chromium } from "playwright-core";
6
+ import {
7
+ launchChromium,
8
+ lifecycle,
9
+ log,
10
+ redactedUrl,
11
+ scrollForLazyContent,
12
+ startStaticServer,
13
+ waitForPageStable,
14
+ } from "./lib.mjs";
15
+ function canvas(width, height) {
16
+ const png = new PNG({ width, height, fill: true });
17
+ png.data.fill(0);
18
+ return png;
19
+ }
20
+
21
+ function copy(source, destination) {
22
+ for (let y = 0; y < source.height; y += 1) {
23
+ for (let x = 0; x < source.width; x += 1) {
24
+ const sourceIndex = (source.width * y + x) << 2;
25
+ const destinationIndex = (destination.width * y + x) << 2;
26
+ source.data.copy(
27
+ destination.data,
28
+ destinationIndex,
29
+ sourceIndex,
30
+ sourceIndex + 4,
31
+ );
32
+ }
33
+ }
34
+ }
35
+
36
+ export async function validate(options) {
37
+ await fs.access(path.join(options.directory, "index.html"));
38
+ const life = lifecycle(options.timeoutMs);
39
+ const results = [];
40
+ try {
41
+ const server = await startStaticServer(options.directory);
42
+ life.add(server.close);
43
+ life.check();
44
+ const { browser, selected } = await launchChromium(chromium, life);
45
+ life.check();
46
+ for (const viewport of options.viewports) {
47
+ life.check();
48
+ log(`Validating ${viewport.name}…`);
49
+ const settings = {
50
+ viewport,
51
+ deviceScaleFactor: 1,
52
+ locale: options.locale,
53
+ colorScheme: options.colorScheme,
54
+ serviceWorkers: "block",
55
+ };
56
+ // Separate contexts ensure the exported page cannot inherit source cookies/storage.
57
+ const sourceContext = await browser.newContext(settings);
58
+ const localContext = await browser.newContext(settings);
59
+ try {
60
+ const source = await sourceContext.newPage();
61
+ source.setDefaultTimeout(10000);
62
+ await source.goto(options.sourceUrl, {
63
+ waitUntil: "domcontentloaded",
64
+ timeout: Math.min(options.timeoutMs, 60000),
65
+ });
66
+ await waitForPageStable(source, options.settleMs);
67
+ const scrollLimited = await scrollForLazyContent(
68
+ source,
69
+ options.maxScrollSteps,
70
+ );
71
+ await waitForPageStable(source, options.settleMs);
72
+ const root = source.locator(options.selector);
73
+ if ((await root.count()) !== 1)
74
+ throw new Error("Source selector is missing or ambiguous");
75
+ const box = await root.boundingBox();
76
+ if (!box || box.width * box.height > 20_000_000)
77
+ throw new Error(
78
+ "Source section is empty or exceeds the 20 megapixel screenshot limit",
79
+ );
80
+ const sourceBuffer = await root.screenshot({
81
+ animations: "disabled",
82
+ caret: "hide",
83
+ });
84
+ const externalRequests = [],
85
+ failedRequests = [],
86
+ errors = [];
87
+ await localContext.route("**/*", async (route) => {
88
+ const url = new URL(route.request().url());
89
+ if (
90
+ ["http:", "https:"].includes(url.protocol) &&
91
+ url.origin !== server.url
92
+ ) {
93
+ if (externalRequests.length < 100)
94
+ externalRequests.push(redactedUrl(url.href));
95
+ if (!options.allowExternal) {
96
+ await route.abort();
97
+ return;
98
+ }
99
+ }
100
+ await route.continue();
101
+ });
102
+ const local = await localContext.newPage();
103
+ local.setDefaultTimeout(10000);
104
+ local.on("pageerror", () => {
105
+ if (errors.length < 100)
106
+ errors.push("Exported page raised a JavaScript error");
107
+ });
108
+ local.on("console", (message) => {
109
+ if (message.type() === "error" && errors.length < 100)
110
+ errors.push("Exported page logged an error");
111
+ });
112
+ local.on("requestfailed", (request) => {
113
+ if (failedRequests.length < 100)
114
+ failedRequests.push(redactedUrl(request.url()));
115
+ });
116
+ local.on("response", (response) => {
117
+ if (response.status() >= 400 && failedRequests.length < 100)
118
+ failedRequests.push(redactedUrl(response.url()));
119
+ });
120
+ await local.goto(`${server.url}/index.html`, {
121
+ waitUntil: "domcontentloaded",
122
+ });
123
+ await waitForPageStable(local, options.settleMs);
124
+ // Legacy root markers remain supported for existing user exports.
125
+ const rootSelector = (await local
126
+ .locator('[data-uiport-root="true"]')
127
+ .count())
128
+ ? '[data-uiport-root="true"]'
129
+ : '[data-effect-extractor-root="true"]';
130
+ const localRoot = local.locator(rootSelector);
131
+ if ((await localRoot.count()) !== 1)
132
+ throw new Error("UIport extraction root is missing or ambiguous");
133
+ const localBox = await localRoot.boundingBox();
134
+ if (!localBox || localBox.width * localBox.height > 20_000_000)
135
+ throw new Error("Exported section exceeds screenshot limit");
136
+ const localBuffer = await localRoot.screenshot({
137
+ animations: "disabled",
138
+ caret: "hide",
139
+ });
140
+ const sourcePng = PNG.sync.read(sourceBuffer),
141
+ localPng = PNG.sync.read(localBuffer);
142
+ const width = Math.max(sourcePng.width, localPng.width),
143
+ height = Math.max(sourcePng.height, localPng.height);
144
+ if (width * height > 20_000_000)
145
+ throw new Error("Comparison exceeds screenshot limit");
146
+ const left = canvas(width, height),
147
+ right = canvas(width, height);
148
+ copy(sourcePng, left);
149
+ copy(localPng, right);
150
+ const differentPixels = pixelmatch(
151
+ left.data,
152
+ right.data,
153
+ null,
154
+ width,
155
+ height,
156
+ { threshold: 0.1, includeAA: false },
157
+ );
158
+ const differenceRatio = differentPixels / (width * height);
159
+ const dimensionsMatch =
160
+ sourcePng.width === localPng.width &&
161
+ Math.abs(sourcePng.height - localPng.height) <= 5;
162
+ const visualPass =
163
+ dimensionsMatch && differenceRatio <= options.maximumDifferenceRatio;
164
+ const networkPass =
165
+ failedRequests.length === 0 &&
166
+ (options.allowExternal || externalRequests.length === 0);
167
+ const captureLimitations = (await local
168
+ .locator("#uiport-metadata")
169
+ .count())
170
+ ? await local
171
+ .locator("#uiport-metadata")
172
+ .evaluate((el) => JSON.parse(el.textContent).limitations)
173
+ : [];
174
+ results.push({
175
+ viewport: viewport.name,
176
+ pass: visualPass && networkPass && !errors.length && !scrollLimited,
177
+ visual: {
178
+ pass: visualPass,
179
+ dimensionsMatch,
180
+ differentPixels,
181
+ differenceRatio,
182
+ maximumDifferenceRatio: options.maximumDifferenceRatio,
183
+ animations: "disabled",
184
+ },
185
+ network: {
186
+ pass: networkPass,
187
+ externalRequests,
188
+ failedRequests,
189
+ externalBlocked: !options.allowExternal,
190
+ },
191
+ behavior: "not-tested",
192
+ captureLimitations,
193
+ errors,
194
+ scrollLimited,
195
+ });
196
+ } finally {
197
+ await sourceContext.close();
198
+ await localContext.close();
199
+ }
200
+ }
201
+ life.check();
202
+ return {
203
+ command: "validate",
204
+ status: results.every((r) => r.pass) ? "complete" : "failed",
205
+ browser: { selected, version: browser.version() },
206
+ behavior: "not-tested",
207
+ results,
208
+ };
209
+ } finally {
210
+ await life.close();
211
+ }
212
+ }
@@ -0,0 +1,20 @@
1
+ ---
2
+ name: uiport
3
+ description: Capture a rendered web section as editable HTML, original CSS and local assets using UIport, then inspect its limitations and validate the result.
4
+ ---
5
+
6
+ # UIport
7
+
8
+ Use for a request to extract an existing web section into local files. Use pages the user owns or has permission to reuse. Do not redesign or invent replacement effects.
9
+
10
+ 1. Inspect the requested URL and choose one CSS selector matching a section container, or body/html for a full page. Include wrappers/decorations that belong to it; html also includes original head scripts.
11
+ 2. Use the installed CLI or source checkout. Once published, `npx uiport@0.1.0` is the pinned form. Before the first release, use `node bin/cli.mjs` from the checkout; never assume an unpublished npm package exists.
12
+ 3. If needed, install the matching browser with `uiport browser install`. No browser download is hidden inside capture.
13
+ 4. Run `uiport capture --url "URL" --selector "SELECTOR" --out "NEW_DIRECTORY" --json`. The default locale is pt-BR. Match locale/color scheme/viewports to the requested source. Never overwrite an existing nonempty directory.
14
+ 5. Read the result. Exit 0 means no known reported limitations, not universal fidelity. Exit 2 means a partial artifact exists; inspect every limitation. Exit 1 means failure. Stdout is JSON, progress is stderr.
15
+ 6. Preview with `uiport serve --dir "DIRECTORY"` and compare with `uiport validate --url "URL" --selector "SELECTOR" --dir "DIRECTORY" --json`, using the same viewport/locale/color-scheme options.
16
+ 7. Inspect hover/focus, animation and relevant interactions separately. Validation disables animation for screenshots and reports behavior as not tested. Source scripts inside the selection, inline handlers and recognized visual library scripts are retained by default. Use capture --omit-scripts to omit them explicitly. Outside initialization, listeners and framework dependencies are not generically recovered; inspect SOURCE_RUNTIME_UNVERIFIED.
17
+ 8. If an effect cannot be isolated from original source, explain the limitation. Do not create a visually similar substitute and call it an extraction. Manual integration of necessary original runtime code is separate work requiring inspection and validation.
18
+ 9. Deliver `index.html` and `assets/` only in the extraction folder. Put reports/screenshots outside it. State the path, verified behavior and remaining limitations.
19
+
20
+ The tool does not generate React/Next components or clone application backends. The project license covers UIport, not third-party captured assets. Never publish customer extracts or credentials as fixtures.
package/uiport.md ADDED
@@ -0,0 +1,155 @@
1
+ # UIport — guia de extração de seções web
2
+
3
+ Você é um agente de extração fiel de seções web. Quando o usuário pedir para clonar, copiar ou extrair uma seção, execute este fluxo até obter um resultado utilizável ou comprovar uma limitação. Não entregue apenas instruções. Use páginas próprias ou cujo uso esteja autorizado.
4
+
5
+ Este é o guia completo do agente. A [skill UIport](skills/uiport/SKILL.md) resume o fluxo para uso nos agentes; ela não substitui as instruções detalhadas abaixo. A [matriz de suporte](docs/support.md) define o que a CLI automatiza na versão 0.1. O fluxo de inspeção e correção manual continua necessário quando a captura automática não for suficiente.
6
+
7
+ ## Resultado obrigatório
8
+
9
+ Cada extração deve gerar somente:
10
+
11
+ ```text
12
+ site--secao/
13
+ ├── index.html
14
+ └── assets/
15
+ └── recursos locais da captura
16
+ ```
17
+
18
+ Não gere `manifest.json`, relatórios, screenshots, arquivos de evidência, CSS separado, bundles JavaScript novos, pastas de validação ou documentação dentro da pasta entregue. CSS, scripts inline originais e a reprodução de animações suportadas ficam incorporados no `index.html`. Scripts externos originais preservados são recursos referenciados em `assets/`. Temporários de análise ficam fora da entrega e devem ser apagados ao terminar. A CLI incorpora os diagnósticos no próprio HTML, sem criar um relatório separado.
19
+
20
+ O objetivo da revisão manual é manter somente os assets necessários à seção e aos estados verificados. A CLI 0.1 preserva CSS de forma conservadora e pode baixar recursos de regras não usadas pela seção; não presuma que ela já eliminou todos os assets excedentes.
21
+
22
+ ## Regras que não podem ser quebradas
23
+
24
+ 1. Extraia; não redesenhe.
25
+ 2. Preserve textos, DOM, classes, IDs, atributos, SVGs, estilos, valores, timings e easing observados, dentro dos casos suportados. Informe o que precisou ser omitido.
26
+ 3. Não simplifique, não melhore e não substitua um efeito por outro parecido.
27
+ 4. Não invente CSS, keyframes, JavaScript, imagens, estados ou comportamento.
28
+ 5. Localize os recursos necessários em `./assets/` e use caminhos relativos. Dependências que não puderem ser localizadas precisam ser declaradas.
29
+ 6. Não incorpore analytics, trackers, autenticação, pagamentos ou lógica de negócio na entrega. A CLI preserva scripts capturados e handlers inline por padrão para manter o comportamento anterior. Inspecione o código original; use `--omit-scripts` quando quiser omiti-lo. A preservação não isola automaticamente código visual de lógica de negócio, e a omissão não torna uma origem hostil segura.
30
+ 7. Não declare fidelidade completa se partes visuais, interações ou animações estiverem faltando. Um artefato parcial deve ser identificado como parcial, mesmo quando a comparação estática passar.
31
+ 8. Não sobrescreva uma pasta com conteúdo nem publique extrações de clientes, credenciais ou material de terceiros como fixtures do projeto.
32
+
33
+ ## Fluxo interno obrigatório
34
+
35
+ ### 1. Inspecionar a seção original
36
+
37
+ - Abra a URL em navegador com JavaScript habilitado.
38
+ - Aguarde DOM, rede, fontes e imagens estabilizarem dentro de um prazo limitado; não espere indefinidamente por páginas com atividade contínua.
39
+ - Role a página para ativar lazy loading e efeitos de entrada. Inspecione o diagnóstico se o limite de rolagem for atingido.
40
+ - Localize uma única raiz que contenha toda a seção, incluindo elementos decorativos, overlays e backgrounds. O seletor deve encontrar uma única raiz. Use um container para uma seção, `body` para a página visível inteira ou `html` para incluir também os scripts do head; não se trata de crawling de múltiplas páginas.
41
+ - Observe o estado inicial e todas as interações relevantes: entrada, scroll, hover, foco, tabs, accordion, carousel e mousemove.
42
+ - Compare os tamanhos de tela necessários e mantenha viewport, idioma e tema consistentes entre captura e validação.
43
+
44
+ ### 2. Extrair o DOM real
45
+
46
+ - Use o DOM renderizado, não o HTML inicial recebido pelo servidor.
47
+ - Confira wrappers internos, atributos, inline styles, SVG inline, `srcset`, vídeos e estados atuais de formulários. Não transfira valores pessoais ou credenciais para uma entrega compartilhada.
48
+ - Inspecione Shadow DOM aberto: a CLI exporta árvores abertas e estilos suportados, mas isso não garante equivalência de qualquer componente.
49
+ - A CLI exporta o DOM do primeiro viewport. Mudanças estruturais observadas nos demais produzem uma limitação; não presuma que todos os estados responsivos foram recuperados.
50
+ - Canvas/WebGL animado, documentos em iframe e Shadow DOM fechado não têm conversão fiel genérica. A CLI pode preservar um frame estático legível de canvas, desabilita embeds e não inspeciona raízes fechadas. Informe a limitação; não substitua por uma imitação.
51
+
52
+ ### 3. Extrair o CSS real
53
+
54
+ - Incorpore no `<style>` do `index.html` o CSS original necessário. A CLI conserva folhas inteiras para evitar perder dependências; a poda completa exige inspeção manual.
55
+ - Confira variáveis CSS, herança necessária, pseudo-elementos, pseudo-classes, `@font-face`, `@keyframes`, media queries, container queries, `clip-path`, masks, filters e transforms.
56
+ - Mantenha seletores, breakpoints e valores originais. Verifique recursos de `url(...)`, `image-set(...)` e CSS importado.
57
+ - Use estilos computados apenas para diagnosticar regras faltantes; não congele toda a seção em valores de um único viewport.
58
+
59
+ ### 4. Extrair efeitos e animações sem inventar
60
+
61
+ - CSS Animation/Transition: preserve as regras e os `@keyframes` originais e teste os estados de ativação.
62
+ - Web Animations API: confira keyframes, timing, delay, iterations, direction, fill, easing, playback rate e estado observados. A CLI reproduz animações serializáveis em DocumentTimeline; não reconstrói genericamente os eventos que as iniciaram.
63
+ - GSAP, ScrollTrigger, AOS, Lottie, Swiper, Webflow ou outra biblioteca: investigue a biblioteca e a configuração/código original necessários. A CLI preserva scripts do recorte, handlers e scripts de bibliotecas visuais reconhecidas, como o protótipo. Isso não recupera automaticamente inicialização externa ao recorte nem todas as dependências do runtime. Se a demanda incluir a integração manual, isole somente o código visual original necessário, sem incorporar lógica de negócio ou rastreamento, e valide novamente.
64
+ - Framer ou outro runtime proprietário: extraia o comportamento somente quando os dados e o runtime necessários puderem ser inspecionados e isolados. Não recrie com uma animação aproximada. Quando isso não for viável, informe a limitação.
65
+ - Efeitos dependentes de scroll precisam ser testados com espaço real de rolagem, sem inserir conteúdo visual fictício dentro da seção. Qualquer suporte temporário de teste deve ficar fora da entrega.
66
+
67
+ ### 5. Organizar assets
68
+
69
+ - Confira imagens, SVGs externos, fontes e vídeos referenciados pela seção. Scripts externos originais preservados também ficam em assets; código inline continua incorporado ao HTML. Integrações manuais precisam respeitar essa estrutura, sem criar um novo bundle ou comportamento aproximado.
70
+ - Não salve stylesheets separados: incorpore o CSS no HTML e ajuste suas referências locais.
71
+ - Remova recursos excedentes somente após verificar referências e estados responsivos/interativos; uma regra inativa no viewport inicial pode ser necessária em outro estado.
72
+ - O HTML deve continuar funcionando quando a pasta for movida e servida novamente. Inspecione também dependências internas de SVGs baixados, que a CLI não localiza integralmente.
73
+
74
+ ## Ferramenta de captura
75
+
76
+ Use a CLI como ponto de partida, não como autorização para entregar um clone quebrado.
77
+
78
+ Antes da primeira publicação no npm, execute na raiz do repositório:
79
+
80
+ ```sh
81
+ npm ci
82
+ node bin/cli.mjs browser install
83
+ ```
84
+
85
+ Capture em uma pasta nova:
86
+
87
+ ```sh
88
+ node bin/cli.mjs capture --url "<URL>" --selector "<SELETOR>" --out "./extractions/<site>--<secao>" --viewports "1440x900,768x1024,375x812" --locale pt-BR --json
89
+ ```
90
+
91
+ Ajuste `--locale`, `--color-scheme` e `--viewports` conforme a origem e use os mesmos valores na validação. A captura não sobrescreve uma pasta existente com conteúdo. `UIPORT_BROWSER_PATH` permite escolher o executável do navegador; a instalação do Chromium é explícita.
92
+
93
+ Quando `uiport@0.1.0` estiver publicado, os mesmos subcomandos poderão ser executados com `npx uiport@0.1.0` no lugar de `node bin/cli.mjs`. Não presuma que o pacote já está disponível no registro. Consulte os [comandos e opções](README.pt-BR.md) ou execute `node bin/cli.mjs --help`.
94
+
95
+ Leia o diagnóstico antes de entregar:
96
+
97
+ - Capture com retorno **0**: artefato criado sem limitações conhecidas relatadas; não é prova de fidelidade universal.
98
+ - Capture com retorno **2**: artefato parcial criado; investigue cada item de `limitations`.
99
+ - Retorno **1**: falha operacional ou falha das verificações solicitadas no validate.
100
+ - `--json`: resultado em stdout e progresso em stderr. Não confunda um artefato parcial com falha sem saída.
101
+
102
+ O idioma padrão permanece `pt-BR`. `capture --omit-scripts` desativa a cópia de scripts da origem e eventos inline; nesse modo, animações WAAPI observadas continuam podendo ser reproduzidas. Sem essa opção, `SOURCE_RUNTIME_UNVERIFIED` pede inspeção do código preservado.
103
+
104
+ Se houver runtime omitido ou não verificado, recurso não localizado, mudança estrutural responsiva ou canvas dinâmico, investigue a origem antes de concluir.
105
+
106
+ ## Validação obrigatória
107
+
108
+ Execute com as mesmas opções da captura:
109
+
110
+ ```sh
111
+ node bin/cli.mjs validate --dir "./extractions/<site>--<secao>" --url "<URL>" --selector "<SELETOR>" --viewports "1440x900,768x1024,375x812" --locale pt-BR --json
112
+ ```
113
+
114
+ A comparação ocorre em memória, sem arquivos adicionais na entrega. Ela desativa animações para as screenshots, usa tolerâncias documentadas e relata comportamento como `not-tested`. Um retorno 0 comprova somente as verificações visuais/de rede nos estados observados; não elimina limitações da captura.
115
+
116
+ O validador reconhece também a raiz de artefatos do protótipo sem modificar a pasta. As novas capturas usam os marcadores UIport.
117
+
118
+ Abra a saída para inspeção manual:
119
+
120
+ ```sh
121
+ node bin/cli.mjs serve --dir "./extractions/<site>--<secao>"
122
+ ```
123
+
124
+ Verifique interações, animações, hover/foco, responsividade e estados relevantes separadamente. A validação bloqueia requisições HTTP(S) externas da saída por padrão. Usar `--allow-external` não comprova portabilidade offline.
125
+
126
+ Se houver divergência:
127
+
128
+ 1. Inspecione a divergência na página original.
129
+ 2. Identifique a regra, asset, estado ou código original que ficou faltando.
130
+ 3. Ajuste somente o `index.html` ou `assets/`, preservando material observado e respeitando os limites da integração manual.
131
+ 4. Execute a validação novamente e repita a inspeção dos comportamentos afetados.
132
+ 5. Repita até passar nos critérios solicitados ou comprovar e informar a limitação que impede a fidelidade.
133
+
134
+ Não resolva divergências inventando valores ou efeitos, nem afrouxe tolerâncias apenas para fazer o teste passar.
135
+
136
+ ## Entrega
137
+
138
+ Entregue apenas a pasta com `index.html` e `assets/`. Na resposta ao usuário, informe o caminho, os estados/comportamentos efetivamente verificados e as limitações restantes. Não crie um relatório dentro da pasta nem declare equivalência completa com base apenas em screenshots.
139
+
140
+ ## Comando do usuário
141
+
142
+ ```text
143
+ Leia e siga uiport.md. Clone a seção <descrição> de <URL>.
144
+ ```
145
+
146
+ ## Referências para evolução
147
+
148
+ - Instalação e comandos: [README.md](README.md) / [README.pt-BR.md](README.pt-BR.md).
149
+ - Capacidades verificadas e limitações: [docs/support.md](docs/support.md).
150
+ - Skill resumida para agentes: [skills/uiport/SKILL.md](skills/uiport/SKILL.md).
151
+ - Compatibilidade com o protótipo: [docs/migration.md](docs/migration.md).
152
+ - Arquitetura: [docs/architecture.md](docs/architecture.md).
153
+ - Desenvolvimento e contribuição: [CONTRIBUTING.md](CONTRIBUTING.md).
154
+
155
+ Ao evoluir este fluxo, mantenha o guia, a skill e a matriz de suporte coerentes. Novas capacidades automáticas exigem implementação e evidência; uma instrução no guia, por si só, não adiciona suporte à CLI.