leiho 1.0.0-beta.13 → 1.0.0-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -107,6 +107,28 @@ Content-Security-Policy: frame-ancestors 'self' https://your-wordpress.example
107
107
 
108
108
  and must not send `X-Frame-Options: DENY` or `SAMEORIGIN`.
109
109
 
110
+ ## Search engines and AI assistants
111
+
112
+ ```js
113
+ import { leihoGraph, jsonLd, seoMeta } from 'leiho/seo';
114
+ // One schema.org graph per page: site, organization, breadcrumbs, and the
115
+ // item's own nodes (item.seo.jsonld, computed by the plugin).
116
+ const graph = leihoGraph( { url, item, site: { url: 'https://example.com', name: 'Example' }, breadcrumbs } );
117
+ const tag = `<script type="application/ld+json">${ jsonLd( graph ) }</script>`;
118
+ ```
119
+
120
+ After a static build, every page as Markdown (`page.md`), `llms.txt`, `llms-full.txt` and `sitemap.xml` with `hreflang`:
121
+
122
+ ```js
123
+ import { aiReady } from 'leiho/ai-ready'; // Astro integration
124
+ import { buildAiFiles } from 'leiho/ai-ready'; // or call it yourself
125
+ await buildAiFiles( { dir: 'dist', site: 'https://example.com' } );
126
+ ```
127
+
128
+ ```bash
129
+ npx leiho ai-ready --site https://example.com --dir dist
130
+ ```
131
+
110
132
  ## Protocol
111
133
 
112
134
  Messages are `{ ns: 'leiho', type, … }`, sent with an explicit `targetOrigin` and checked against `event.origin`.
package/bin/leiho.js CHANGED
@@ -4,12 +4,14 @@
4
4
  *
5
5
  * npx leiho types [--url https://cms.example.com] [--out src/leiho.d.ts]
6
6
  * npx leiho pull [--url https://cms.example.com] [--out .leiho/content.json]
7
+ * npx leiho ai-ready --site https://example.com [--dir dist] [--locales en,fr]
7
8
  *
8
9
  * L'adresse du CMS et le jeton se lisent aussi dans LEIHO_URL et LEIHO_TOKEN.
9
10
  */
10
11
  import fs from 'node:fs/promises';
11
12
  import path from 'node:path';
12
13
  import { exportUrl, loadLeihoContent } from '../src/content.js';
14
+ import { buildAiFiles } from '../src/ai-ready.js';
13
15
 
14
16
  const [ command, ...rest ] = process.argv.slice( 2 );
15
17
  const args = {};
@@ -43,10 +45,22 @@ async function pull() {
43
45
  console.log( 'leiho: ' + data.items.length + ' items (' + source + ') in ' + out );
44
46
  }
45
47
 
46
- const commands = { types, pull };
48
+ // Après un build statique : pages en Markdown, llms.txt, llms-full.txt, sitemap.xml.
49
+ async function aiReady() {
50
+ await buildAiFiles( {
51
+ dir: args.dir || 'dist',
52
+ site: args.site || process.env.SITE_URL,
53
+ locales: args.locales ? args.locales.split( ',' ) : undefined,
54
+ exclude: args.exclude ? args.exclude.split( ',' ) : undefined,
55
+ sitemap: args.sitemap !== 'false',
56
+ logger: { info: ( message ) => console.log( 'leiho: ' + message ) },
57
+ } );
58
+ }
59
+
60
+ const commands = { types, pull, 'ai-ready': aiReady };
47
61
 
48
62
  if ( ! commands[ command ] ) {
49
- console.log( 'Usage: leiho <types|pull> [--url https://cms.example.com] [--out file] [--token …]' );
63
+ console.log( 'Usage: leiho <types|pull> [--url https://cms.example.com] [--out file] [--token …]\n leiho ai-ready --site https://example.com [--dir dist] [--locales en,fr] [--exclude /drafts] [--sitemap false]' );
50
64
  process.exit( command ? 1 : 0 );
51
65
  }
52
66
 
@@ -292,22 +292,68 @@
292
292
  * Application des valeurs
293
293
  * ------------------------------------------------------------------ */
294
294
 
295
+ // Liste blanche : seul ce qu'un texte riche contient passe. Une liste noire
296
+ // laisse toujours une porte (noscript, svg/math, schémas d'URL exotiques).
297
+ const ALLOWED_TAGS = new Set( [
298
+ 'A', 'ABBR', 'B', 'BLOCKQUOTE', 'BR', 'CAPTION', 'CITE', 'CODE', 'DD', 'DEL', 'DIV', 'DL', 'DT', 'EM', 'FIGCAPTION',
299
+ 'FIGURE', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'HR', 'I', 'IMG', 'INS', 'KBD', 'LI', 'MARK', 'OL', 'P', 'PRE', 'Q',
300
+ 'S', 'SMALL', 'SPAN', 'STRONG', 'SUB', 'SUP', 'TABLE', 'TBODY', 'TD', 'TFOOT', 'TH', 'THEAD', 'TR', 'U', 'UL',
301
+ ] );
302
+ // Hors liste blanche et retirées avec leur contenu (code, documents imbriqués).
303
+ const DROPPED_TAGS = new Set( [ ...BANNED_TAGS.map( ( t ) => t.toUpperCase() ), 'NOSCRIPT', 'NOEMBED', 'NOFRAMES', 'TEMPLATE', 'SVG', 'MATH', 'XMP', 'TEXTAREA', 'TITLE', 'SELECT', 'OBJECT' ] );
304
+ const ALLOWED_ATTRS = new Set( [ 'href', 'src', 'alt', 'title', 'class', 'width', 'height', 'target', 'rel', 'colspan', 'rowspan', 'lang', 'dir', 'start', 'reversed', 'loading', 'decoding', 'srcset', 'sizes', 'id', 'style' ] );
305
+
306
+ /** Adresse sûre : http(s), mailto, tel ou relative. */
307
+ function safeUrl( value ) {
308
+ const url = String( null == value ? '' : value ).replace( /[\u0000-\u0020\u007f-\u009f]/g, '' );
309
+ const scheme = url.match( /^([a-z][a-z0-9+.-]*):/i );
310
+ return ! scheme || /^(https?|mailto|tel)$/i.test( scheme[ 1 ] ) ? String( value ) : '';
311
+ }
312
+
295
313
  function sanitizeHtml( html ) {
296
- const doc = document.implementation.createHTMLDocument( '' );
297
- doc.body.innerHTML = String( null == html ? '' : html );
298
- doc.body.querySelectorAll( BANNED_TAGS.join( ',' ) ).forEach( ( el ) => el.remove() );
299
- doc.body.querySelectorAll( '*' ).forEach( ( el ) => {
300
- [ ...el.attributes ].forEach( ( attr ) => {
301
- const name = attr.name.toLowerCase();
302
- const value = attr.value.replace( /\s+/g, '' ).toLowerCase();
303
- if ( 0 === name.indexOf( 'on' ) ) {
304
- el.removeAttribute( attr.name );
305
- } else if ( ( 'href' === name || 'src' === name || 'xlink:href' === name ) && 0 === value.indexOf( 'javascript:' ) ) {
306
- el.removeAttribute( attr.name );
314
+ const source = new DOMParser().parseFromString( '<body>' + String( null == html ? '' : html ) + '</body>', 'text/html' ).body;
315
+ const clean = ( node, into ) => {
316
+ node.childNodes.forEach( ( child ) => {
317
+ if ( child.nodeType === Node.TEXT_NODE ) {
318
+ into.appendChild( document.createTextNode( child.nodeValue ) );
319
+ return;
320
+ }
321
+ if ( child.nodeType !== Node.ELEMENT_NODE ) {
322
+ return;
323
+ }
324
+ if ( ! ALLOWED_TAGS.has( child.tagName ) ) {
325
+ // Balise inconnue : son texte reste, sauf pour ce qui n'en a pas à montrer.
326
+ if ( ! DROPPED_TAGS.has( child.tagName.toUpperCase() ) ) {
327
+ clean( child, into );
328
+ }
329
+ return;
307
330
  }
331
+ const el = document.createElement( child.tagName );
332
+ [ ...child.attributes ].forEach( ( a ) => {
333
+ const name = a.name.toLowerCase();
334
+ if ( ! ALLOWED_ATTRS.has( name ) ) {
335
+ return;
336
+ }
337
+ if ( 'href' === name || 'src' === name ) {
338
+ const url = safeUrl( a.value );
339
+ if ( url ) {
340
+ el.setAttribute( name, url );
341
+ }
342
+ } else if ( 'srcset' === name ) {
343
+ if ( ! /(^|,)\s*[a-z][a-z0-9+.-]*:/i.test( a.value ) || a.value.split( ',' ).every( ( part ) => safeUrl( part.trim().split( /\s+/ )[ 0 ] ) ) ) {
344
+ el.setAttribute( name, a.value );
345
+ }
346
+ } else {
347
+ el.setAttribute( name, a.value );
348
+ }
349
+ } );
350
+ clean( child, el );
351
+ into.appendChild( el );
308
352
  } );
309
- } );
310
- return doc.body.innerHTML;
353
+ };
354
+ const out = document.createElement( 'div' );
355
+ clean( source, out );
356
+ return out.innerHTML;
311
357
  }
312
358
 
313
359
  /**
@@ -330,12 +376,13 @@
330
376
  if ( 'image' === fieldType ) {
331
377
  const img = 'IMG' === el.tagName ? el : el.querySelector( 'img' );
332
378
  if ( img ) {
333
- if ( img.getAttribute( 'src' ) !== ( value || '' ) ) {
334
- img.setAttribute( 'src', value || '' );
379
+ if ( img.getAttribute( 'src' ) !== safeUrl( value || '' ) ) {
380
+ img.setAttribute( 'src', safeUrl( value || '' ) );
335
381
  img.removeAttribute( 'srcset' );
336
382
  }
337
383
  } else {
338
- el.style.backgroundImage = value ? 'url("' + value + '")' : '';
384
+ const src = safeUrl( value || '' );
385
+ el.style.backgroundImage = src ? 'url("' + src.replace( /["\\\n]/g, '' ) + '")' : '';
339
386
  }
340
387
  } else if ( 'color_picker' === fieldType ) {
341
388
  el.style.setProperty( attr( el, 'style' ) || 'color', value || '' );
@@ -343,7 +390,7 @@
343
390
  const link = 'A' === el.tagName ? el : el.querySelector( 'a' );
344
391
  const data = value && 'object' === typeof value ? value : { url: value };
345
392
  if ( link ) {
346
- link.setAttribute( 'href', data.url || '' );
393
+ link.setAttribute( 'href', safeUrl( data.url || '' ) );
347
394
  if ( data.target ) {
348
395
  link.setAttribute( 'target', data.target );
349
396
  } else {
@@ -505,6 +552,9 @@
505
552
  } catch ( e ) {
506
553
  return;
507
554
  }
555
+ if ( ! /^https?:$/.test( url.protocol ) ) {
556
+ return;
557
+ }
508
558
  send( { type: 'navigate', href: url.href, path: url.pathname, external: url.origin !== window.location.origin } );
509
559
  return;
510
560
  }
@@ -544,7 +594,7 @@
544
594
  }
545
595
 
546
596
  window.addEventListener( 'message', ( event ) => {
547
- if ( event.origin !== wpOrigin || ! event.data || event.data.ns !== NS ) {
597
+ if ( event.origin !== wpOrigin || event.source !== window.parent || ! event.data || event.data.ns !== NS ) {
548
598
  return;
549
599
  }
550
600
  const data = event.data;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "leiho",
3
- "version": "1.0.0-beta.13",
3
+ "version": "1.0.0-rc.2",
4
4
  "description": "Pont postMessage de l'éditeur visuel Leiho : rend n'importe quel site (React, Next.js, Remix, Vite, Nuxt, SvelteKit, Astro, HTML) éditable depuis WordPress. Zéro dépendance, inactif hors de l'éditeur.",
5
5
  "keywords": [
6
6
  "wordpress",
@@ -13,7 +13,10 @@
13
13
  "remix",
14
14
  "vite",
15
15
  "nuxt",
16
- "sveltekit"
16
+ "sveltekit",
17
+ "llms.txt",
18
+ "json-ld",
19
+ "seo"
17
20
  ],
18
21
  "license": "GPL-2.0-or-later",
19
22
  "author": "Pixelers (https://pixelers.fr)",
@@ -34,6 +37,12 @@
34
37
  },
35
38
  "./attrs": {
36
39
  "import": "./src/attrs.js"
40
+ },
41
+ "./seo": {
42
+ "import": "./src/seo.js"
43
+ },
44
+ "./ai-ready": {
45
+ "import": "./src/ai-ready.js"
37
46
  }
38
47
  },
39
48
  "scripts": {
@@ -0,0 +1,488 @@
1
+ /**
2
+ * Un site statique prêt pour les assistants IA, après le build (Node 18+) :
3
+ *
4
+ * - chaque page en Markdown, à côté de son HTML (docs/install/index.html → docs/install.md) ;
5
+ * - llms.txt et llms-full.txt (llmstxt.org), un par langue ;
6
+ * - sitemap.xml avec les autres langues de chaque page (hreflang) et sa date.
7
+ *
8
+ * import { buildAiFiles } from 'leiho/ai-ready';
9
+ * await buildAiFiles( { dir: 'dist', site: 'https://example.com' } );
10
+ *
11
+ * // Astro : astro.config.mjs
12
+ * import { aiReady } from 'leiho/ai-ready';
13
+ * export default defineConfig( { site: 'https://example.com', integrations: [ aiReady() ] } );
14
+ *
15
+ * // Tout autre build statique : npx leiho ai-ready --dir out --site https://example.com
16
+ *
17
+ * Le Markdown vient du <main> de chaque page déjà rendue : ce que lit un agent
18
+ * est ce que lit un visiteur, sans second gabarit. Les illustrations
19
+ * (aria-hidden, svg, canvas, data-md-skip) sont laissées de côté.
20
+ */
21
+ import { readdir, readFile, writeFile } from 'node:fs/promises';
22
+ import { join, relative, sep } from 'node:path';
23
+ import { fileURLToPath } from 'node:url';
24
+ import { findNode, findNodes, parseHtml, textOf } from './html.js';
25
+
26
+ const BLOCK = new Set( [
27
+ 'address', 'article', 'aside', 'blockquote', 'details', 'dd', 'div', 'dl', 'dt', 'fieldset', 'figcaption', 'figure',
28
+ 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'hgroup', 'hr', 'li', 'main', 'nav', 'ol', 'p', 'pre',
29
+ 'section', 'summary', 'table', 'ul',
30
+ ] );
31
+ const SKIP_TAGS = new Set( [ 'script', 'style', 'svg', 'canvas', 'button', 'template', 'noscript', 'iframe', 'video', 'audio', 'input', 'select', 'textarea', 'aside', 'nav', 'dialog' ] );
32
+
33
+ const classes = ( n ) => ( n.attrs?.class || '' ).split( /\s+/ ).filter( Boolean );
34
+ const isElement = ( n, tag ) => n.type === 'element' && ( ! tag || n.tag === tag );
35
+
36
+ /**
37
+ * Convertisseur HTML → Markdown.
38
+ *
39
+ * @param {object} [options]
40
+ * @param {string} [options.site] Adresse du site : liens relatifs rendus absolus.
41
+ * @param {string[]} [options.skipClasses] Classes d'éléments à ignorer (illustrations).
42
+ * @returns {(node:any)=>string}
43
+ */
44
+ export function createConverter( options = {} ) {
45
+ const site = ( options.site || '' ).replace( /\/+$/, '' );
46
+ const skipClasses = new Set( options.skipClasses || [] );
47
+
48
+ const skipped = ( n ) => {
49
+ if ( n.type !== 'element' ) {
50
+ return n.type !== 'text';
51
+ }
52
+ const a = n.attrs;
53
+ return SKIP_TAGS.has( n.tag ) || a[ 'aria-hidden' ] === 'true' || 'hidden' in a || 'data-md-skip' in a || classes( n ).some( ( c ) => skipClasses.has( c ) );
54
+ };
55
+ const isBlock = ( n ) => n.type === 'element' && ( BLOCK.has( n.tag ) || n.attrs.role === 'table' || n.attrs.role === 'row' );
56
+
57
+ const abs = ( href ) => {
58
+ if ( ! href || href.startsWith( '#' ) || /^[a-z]+:/i.test( href ) ) {
59
+ return href;
60
+ }
61
+ return site + ( href.startsWith( '/' ) ? href : '/' + href );
62
+ };
63
+ const squash = ( s ) => s.replace( /\s+/g, ' ' ).trim();
64
+ const tidy = ( s ) => s.replace( /[ \t]+/g, ' ' ).replace( / *\n */g, '\n' ).trim();
65
+
66
+ function inline( n ) {
67
+ if ( n.type === 'text' ) {
68
+ return n.value.replace( /\s+/g, ' ' );
69
+ }
70
+ if ( skipped( n ) ) {
71
+ return '';
72
+ }
73
+ const inner = () => ( n.children || [] ).map( inline ).join( '' );
74
+ switch ( n.tag ) {
75
+ case 'br':
76
+ return '\n';
77
+ case 'strong':
78
+ case 'b': {
79
+ const t = inner().trim();
80
+ return t ? `**${ t }**` : '';
81
+ }
82
+ case 'em':
83
+ case 'i': {
84
+ const t = inner().trim();
85
+ return t ? `_${ t }_` : '';
86
+ }
87
+ case 'code': {
88
+ const t = textOf( n );
89
+ return t.includes( '`' ) ? '`` ' + t + ' ``' : '`' + t + '`';
90
+ }
91
+ case 'img':
92
+ return n.attrs.alt ? `![${ n.attrs.alt }](${ abs( n.attrs.src ) })` : '';
93
+ case 'a': {
94
+ const t = squash( inner() );
95
+ const href = n.attrs.href;
96
+ return ! t || ! href || href.startsWith( '#' ) ? t : `[${ t }](${ abs( href ) })`;
97
+ }
98
+ default:
99
+ return inner();
100
+ }
101
+ }
102
+
103
+ // Enfants d'un conteneur : une suite d'éléments en ligne forme un paragraphe,
104
+ // une suite de liens seuls (cartes, logos) une liste.
105
+ function children( n ) {
106
+ const out = [];
107
+ let run = '';
108
+ let links = [];
109
+ let other = false;
110
+ const flush = () => {
111
+ if ( links.length > 1 && ! other ) {
112
+ out.push( links.map( ( l ) => '- ' + l ).join( '\n' ) );
113
+ } else if ( tidy( run ) ) {
114
+ out.push( tidy( run ) );
115
+ }
116
+ run = '';
117
+ links = [];
118
+ other = false;
119
+ };
120
+ for ( const c of n.children || [] ) {
121
+ if ( skipped( c ) ) {
122
+ continue;
123
+ }
124
+ if ( isBlock( c ) || ( isElement( c, 'a' ) && findNode( { children: c.children }, isBlock ) ) ) {
125
+ flush();
126
+ out.push( ...block( c ) );
127
+ continue;
128
+ }
129
+ const piece = inline( c );
130
+ if ( isElement( c, 'a' ) && piece.trim() ) {
131
+ links.push( piece.trim() );
132
+ } else if ( piece.trim() ) {
133
+ other = true;
134
+ }
135
+ run += run && /[\])]$/.test( run ) && piece.startsWith( '[' ) ? ' ' + piece : piece;
136
+ }
137
+ flush();
138
+ return out;
139
+ }
140
+
141
+ function table( rows ) {
142
+ const grid = rows.map( ( r ) => ( r.children || [] ).filter( ( c ) => c.type === 'element' && ! skipped( c ) ).map( ( c ) => children( c ).join( ' ' ).replace( /\|/g, '\\|' ).replace( /\n/g, ' ' ) ) );
143
+ if ( ! grid.length ) {
144
+ return [];
145
+ }
146
+ const width = Math.max( ...grid.map( ( r ) => r.length ) );
147
+ const line = ( r ) => `| ${ [ ...r, ...Array( width - r.length ).fill( '' ) ].join( ' | ' ) } |`;
148
+ return [ [ line( grid[ 0 ] ), line( Array( width ).fill( '---' ) ), ...grid.slice( 1 ).map( line ) ].join( '\n' ) ];
149
+ }
150
+
151
+ function list( n, ordered ) {
152
+ const items = ( n.children || [] ).filter( ( c ) => isElement( c, 'li' ) && ! skipped( c ) );
153
+ const lines = items.map( ( li, i ) => {
154
+ const marker = ordered ? `${ i + 1 }. ` : '- ';
155
+ return marker + children( li ).join( '\n' ).split( '\n' ).join( '\n' + ' '.repeat( marker.length ) );
156
+ } );
157
+ return lines.length ? [ lines.join( '\n' ) ] : [];
158
+ }
159
+
160
+ // Langage d'un bloc de code : class="language-x", data-language, ou légende de la figure (fichier ou langage).
161
+ function codeLang( pre, figure ) {
162
+ const code = findNode( pre, ( k ) => isElement( k, 'code' ) );
163
+ for ( const el of [ code, pre ] ) {
164
+ const lang = el?.attrs[ 'data-language' ] || classes( el || { attrs: {} } ).find( ( c ) => c.startsWith( 'language-' ) )?.slice( 9 );
165
+ if ( lang ) {
166
+ return lang;
167
+ }
168
+ }
169
+ const cap = figure && findNode( figure, ( k ) => isElement( k, 'figcaption' ) );
170
+ const label = cap ? textOf( findNode( cap, ( k ) => isElement( k, 'span' ) ) || cap ).trim() : '';
171
+ if ( ! label || label === 'code' || /\s/.test( label ) ) {
172
+ return '';
173
+ }
174
+ const ext = label.includes( '.' ) ? label.split( '.' ).pop() : label;
175
+ return { mjs: 'js', cjs: 'js', sh: 'bash', yml: 'yaml', md: 'markdown' }[ ext ] || ext;
176
+ }
177
+
178
+ function block( n, figure ) {
179
+ const role = n.attrs?.role;
180
+ if ( role === 'table' ) {
181
+ return table( findNodes( n, ( k ) => k.type === 'element' && k.attrs.role === 'row' ) );
182
+ }
183
+ switch ( n.tag ) {
184
+ case 'h1':
185
+ case 'h2':
186
+ case 'h3':
187
+ case 'h4':
188
+ case 'h5':
189
+ case 'h6': {
190
+ const t = squash( ( n.children || [] ).map( inline ).join( '' ) );
191
+ return t ? [ '#'.repeat( Number( n.tag[ 1 ] ) ) + ' ' + t ] : [];
192
+ }
193
+ case 'p':
194
+ case 'dt':
195
+ case 'dd':
196
+ case 'summary': {
197
+ const t = tidy( ( n.children || [] ).map( inline ).join( '' ) );
198
+ return t ? [ t ] : [];
199
+ }
200
+ case 'ul':
201
+ return list( n, false );
202
+ case 'ol':
203
+ return list( n, true );
204
+ case 'hr':
205
+ return [ '---' ];
206
+ case 'pre': {
207
+ const code = textOf( n ).replace( /\n+$/, '' );
208
+ const fence = code.includes( '```' ) ? '````' : '```';
209
+ return [ `${ fence }${ codeLang( n, figure ) }\n${ code }\n${ fence }` ];
210
+ }
211
+ case 'blockquote':
212
+ return [ children( n ).join( '\n\n' ).split( '\n' ).map( ( l ) => '> ' + l ).join( '\n' ) ];
213
+ case 'table':
214
+ return table( findNodes( n, ( k ) => isElement( k, 'tr' ) ) );
215
+ case 'figure': {
216
+ const pre = findNode( n, ( k ) => isElement( k, 'pre' ) );
217
+ if ( pre ) {
218
+ return block( pre, n );
219
+ }
220
+ return children( n );
221
+ }
222
+ case 'figcaption':
223
+ return [];
224
+ case 'a': {
225
+ // Carte cliquable : son titre devient le lien.
226
+ const parts = children( n );
227
+ const href = abs( n.attrs.href );
228
+ if ( ! parts.length || ! href || href.startsWith( '#' ) ) {
229
+ return parts;
230
+ }
231
+ const m = parts[ 0 ].match( /^(#+) (.*)$/ );
232
+ parts[ 0 ] = m ? `${ m[ 1 ] } [${ m[ 2 ] }](${ href })` : `[${ parts[ 0 ].replace( /\n/g, ' ' ) }](${ href })`;
233
+ return parts;
234
+ }
235
+ default:
236
+ return children( n );
237
+ }
238
+ }
239
+
240
+ return ( node ) => block( node ).join( '\n\n' ).replace( /\n{3,}/g, '\n\n' ).trim() + '\n';
241
+ }
242
+
243
+ /**
244
+ * Adresse Markdown d'une page : / → /index.md, /docs/install → /docs/install.md.
245
+ *
246
+ * @param {string} path
247
+ * @returns {string}
248
+ */
249
+ export function markdownPath( path ) {
250
+ const clean = path.replace( /\/+$/, '' );
251
+ return ( clean || '/index' ) + '.md';
252
+ }
253
+
254
+ async function htmlFiles( dir ) {
255
+ const out = [];
256
+ for ( const e of await readdir( dir, { withFileTypes: true } ) ) {
257
+ const p = join( dir, e.name );
258
+ if ( e.isDirectory() ) {
259
+ out.push( ...( await htmlFiles( p ) ) );
260
+ } else if ( e.name === 'index.html' ) {
261
+ out.push( p );
262
+ }
263
+ }
264
+ return out;
265
+ }
266
+
267
+ const xml = ( s ) => String( s ).replace( /&/g, '&amp;' ).replace( /</g, '&lt;' ).replace( />/g, '&gt;' ).replace( /"/g, '&quot;' );
268
+ const meta = ( tree, test ) => findNode( tree, ( n ) => n.type === 'element' && test( n.tag, n.attrs ) );
269
+
270
+ /**
271
+ * Écrit les fichiers pour les IA dans un dossier de build.
272
+ *
273
+ * @param {object} options
274
+ * @param {string} options.dir Dossier du build (dist, out…).
275
+ * @param {string} options.site Adresse publique du site.
276
+ * @param {string[]} [options.locales] Langues, la première étant celle sans préfixe. Défaut : lues dans <html lang>.
277
+ * @param {string} [options.defaultLocale] Langue sans préfixe d'adresse. Défaut : locales[0].
278
+ * @param {string} [options.name] Nom du site en tête de llms.txt. Défaut : og:site_name de l'accueil.
279
+ * @param {Record<string,string>|string} [options.intro] Paragraphe d'introduction de llms.txt, par langue.
280
+ * @param {Record<string,Record<string,string>>} [options.sections] Titre de rubrique par premier segment d'adresse et par langue ({ en: { docs: 'Docs' } }).
281
+ * @param {string[]} [options.optional] Rubriques secondaires, rangées sous « Optional ».
282
+ * @param {string[]} [options.exclude] Chemins (ou débuts de chemin) à laisser de côté.
283
+ * @param {string[]} [options.skipClasses] Classes d'éléments à ignorer dans le Markdown.
284
+ * @param {string} [options.selector] Élément qui porte le contenu : 'main' (défaut).
285
+ * @param {boolean} [options.sitemap] Écrire sitemap.xml (défaut true).
286
+ * @param {{info:Function}} [options.logger]
287
+ * @returns {Promise<{pages:number}>}
288
+ */
289
+ export async function buildAiFiles( options ) {
290
+ const root = options.dir instanceof URL ? fileURLToPath( options.dir ) : options.dir;
291
+ const site = String( options.site || '' ).replace( /\/+$/, '' );
292
+ if ( ! site ) {
293
+ throw new Error( 'Leiho: buildAiFiles needs the public address of the site (option `site`).' );
294
+ }
295
+ const selector = options.selector || 'main';
296
+ const exclude = options.exclude || [];
297
+ const toMarkdown = createConverter( { site, skipClasses: options.skipClasses } );
298
+ const pages = [];
299
+
300
+ for ( const file of await htmlFiles( root ) ) {
301
+ const path = '/' + relative( root, file ).split( sep ).slice( 0, -1 ).join( '/' );
302
+ if ( exclude.some( ( x ) => path === x || path.startsWith( x.replace( /\/?$/, '/' ) ) ) ) {
303
+ continue;
304
+ }
305
+ const tree = parseHtml( await readFile( file, 'utf8' ) );
306
+ const main = findNode( tree, ( n ) => isElement( n, selector ) );
307
+ const robots = meta( tree, ( t, a ) => t === 'meta' && a.name === 'robots' )?.attrs.content || '';
308
+ if ( ! main || /noindex/i.test( robots ) ) {
309
+ continue;
310
+ }
311
+
312
+ const lang = findNode( tree, ( n ) => isElement( n, 'html' ) )?.attrs.lang || '';
313
+ const title = textOf( meta( tree, ( t ) => t === 'title' ) || { children: [] } ).trim();
314
+ const description = meta( tree, ( t, a ) => t === 'meta' && a.name === 'description' )?.attrs.content || '';
315
+ const modified = meta( tree, ( t, a ) => t === 'meta' && a.property === 'article:modified_time' )?.attrs.content || '';
316
+ const siteName = meta( tree, ( t, a ) => t === 'meta' && a.property === 'og:site_name' )?.attrs.content || '';
317
+ const url = site + ( path === '/' ? '' : path );
318
+ const md = markdownPath( path );
319
+ const body = toMarkdown( main );
320
+
321
+ const front = [ '---', `title: ${ JSON.stringify( title ) }` ];
322
+ if ( description ) {
323
+ front.push( `description: ${ JSON.stringify( description ) }` );
324
+ }
325
+ front.push( `url: ${ url }` );
326
+ if ( lang ) {
327
+ front.push( `lang: ${ lang }` );
328
+ }
329
+ if ( modified ) {
330
+ front.push( `updated: ${ modified.slice( 0, 10 ) }` );
331
+ }
332
+ front.push( '---', '' );
333
+ await writeFile( join( root, md.slice( 1 ) ), front.join( '\n' ) + body );
334
+
335
+ pages.push( { path, url, md: site + md, lang, title, description, modified, siteName, body } );
336
+ }
337
+
338
+ // Langues : celles données, sinon celles des pages (la langue de l'accueil d'abord).
339
+ const home = pages.find( ( p ) => p.path === '/' );
340
+ const short = ( l ) => String( l || '' ).toLowerCase().split( '-' )[ 0 ];
341
+ const locales = options.locales || [ ...new Set( [ short( home?.lang ), ...pages.map( ( p ) => short( p.lang ) ) ].filter( Boolean ) ) ];
342
+ const defaultLocale = options.defaultLocale || locales[ 0 ] || '';
343
+ const localeOf = ( path ) => {
344
+ const first = path.split( '/' )[ 1 ];
345
+ return locales.includes( first ) && first !== defaultLocale ? first : defaultLocale;
346
+ };
347
+ const base = ( path ) => {
348
+ const l = localeOf( path );
349
+ return l === defaultLocale ? path : path.slice( l.length + 1 ) || '/';
350
+ };
351
+
352
+ // Ordre : celui des liens de l'accueil (menus, pied de page), puis alphabétique.
353
+ const order = new Map();
354
+ for ( const p of pages.filter( ( q ) => base( q.path ) === '/' || base( q.path ).split( '/' ).length === 2 ) ) {
355
+ const tree = parseHtml( await readFile( join( root, p.path.slice( 1 ), 'index.html' ), 'utf8' ) );
356
+ for ( const a of findNodes( tree, ( n ) => isElement( n, 'a' ) ) ) {
357
+ const href = String( a.attrs.href || '' ).replace( /^https?:\/\/[^/]+/, '' ).replace( /\/$/, '' ) || '/';
358
+ if ( href.startsWith( '/' ) && ! order.has( href ) ) {
359
+ order.set( href, order.size );
360
+ }
361
+ }
362
+ }
363
+ const rank = ( p ) => ( order.has( p.path ) ? order.get( p.path ) : 1e6 );
364
+ pages.sort( ( a, b ) => rank( a ) - rank( b ) || a.path.localeCompare( b.path ) );
365
+
366
+ const label = ( p ) => p.title.replace( /\s+[·|–—-]\s+[^·|–—-]+$/, '' ) || p.path;
367
+ const optional = options.optional || [];
368
+
369
+ for ( const locale of locales.length ? locales : [ '' ] ) {
370
+ const mine = pages.filter( ( p ) => localeOf( p.path ) === locale );
371
+ const prefix = locale && locale !== defaultLocale ? '/' + locale : '';
372
+ const homePage = mine.find( ( p ) => base( p.path ) === '/' );
373
+ const name = options.name || homePage?.siteName || label( homePage || { title: '', path: site } );
374
+ const intro = typeof options.intro === 'string' ? options.intro : options.intro?.[ locale ] || '';
375
+ const sections = options.sections?.[ locale ] || {};
376
+ const head = [ `# ${ name }`, '' ];
377
+ if ( homePage?.description ) {
378
+ head.push( `> ${ homePage.description }`, '' );
379
+ }
380
+ if ( intro ) {
381
+ head.push( intro, '' );
382
+ }
383
+
384
+ const groups = new Map();
385
+ for ( const p of mine ) {
386
+ const b = base( p.path );
387
+ if ( b === '/' ) {
388
+ continue;
389
+ }
390
+ const seg = b.split( '/' )[ 1 ];
391
+ const key = optional.includes( seg ) ? '\u0000optional' : b.split( '/' ).length > 2 || sections[ seg ] ? seg : '\u0000pages';
392
+ if ( ! groups.has( key ) ) {
393
+ groups.set( key, [] );
394
+ }
395
+ groups.get( key ).push( p );
396
+ }
397
+ const title = ( key ) => {
398
+ if ( key === '\u0000optional' ) {
399
+ return 'Optional';
400
+ }
401
+ if ( key === '\u0000pages' ) {
402
+ return sections.pages || 'Pages';
403
+ }
404
+ return sections[ key ] || key.replace( /[-_]+/g, ' ' ).replace( /^./, ( c ) => c.toUpperCase() );
405
+ };
406
+ const keys = [ ...Object.keys( sections ).filter( ( k ) => groups.has( k ) ), ...[ ...groups.keys() ].filter( ( k ) => ! ( k in sections ) && ! k.startsWith( '\u0000' ) ), '\u0000pages', '\u0000optional' ];
407
+
408
+ const lines = [ ...head ];
409
+ for ( const key of keys ) {
410
+ // Page de la rubrique d'abord, sans doublon de titre (/docs = /docs/introduction).
411
+ const list = ( groups.get( key ) || [] )
412
+ .sort( ( a, b ) => base( a.path ).split( '/' ).length - base( b.path ).split( '/' ).length )
413
+ .filter( ( p, i, all ) => all.findIndex( ( q ) => label( q ) === label( p ) ) === i );
414
+ if ( ! list.length ) {
415
+ continue;
416
+ }
417
+ lines.push( `## ${ title( key ) }`, '' );
418
+ for ( const p of list ) {
419
+ lines.push( `- [${ label( p ) }](${ p.md })${ p.description ? ': ' + p.description.replace( /\s+/g, ' ' ) : '' }` );
420
+ }
421
+ lines.push( '' );
422
+ }
423
+ const others = locales.filter( ( l ) => l !== locale );
424
+ if ( others.length ) {
425
+ lines.push( `## ${ sections.languages || 'Other languages' }`, '' );
426
+ for ( const l of others ) {
427
+ lines.push( `- [${ l.toUpperCase() }](${ site }${ l === defaultLocale ? '' : '/' + l }/llms.txt)` );
428
+ }
429
+ lines.push( '' );
430
+ }
431
+ await writeFile( join( root, prefix.slice( 1 ), 'llms.txt' ), lines.join( '\n' ) );
432
+
433
+ const full = [ ...head ];
434
+ for ( const p of mine ) {
435
+ full.push( '---', '', `Source: ${ p.url }${ p.modified ? ` (updated ${ p.modified.slice( 0, 10 ) })` : '' }`, '', p.body );
436
+ }
437
+ await writeFile( join( root, prefix.slice( 1 ), 'llms-full.txt' ), full.join( '\n' ) );
438
+ }
439
+
440
+ if ( options.sitemap !== false ) {
441
+ const byBase = new Map();
442
+ for ( const p of pages ) {
443
+ const b = base( p.path );
444
+ if ( ! byBase.has( b ) ) {
445
+ byBase.set( b, {} );
446
+ }
447
+ byBase.get( b )[ localeOf( p.path ) ] = p;
448
+ }
449
+ const urls = [];
450
+ for ( const set of byBase.values() ) {
451
+ const many = Object.keys( set ).length > 1;
452
+ for ( const p of Object.values( set ) ) {
453
+ const alts = many ? Object.entries( set ).map( ( [ l, q ] ) => ` <xhtml:link rel="alternate" hreflang="${ l }" href="${ xml( q.url ) }"/>` ) : [];
454
+ if ( many && set[ defaultLocale ] ) {
455
+ alts.push( ` <xhtml:link rel="alternate" hreflang="x-default" href="${ xml( set[ defaultLocale ].url ) }"/>` );
456
+ }
457
+ urls.push( [ ' <url>', ` <loc>${ xml( p.url ) }</loc>`, ...( p.modified ? [ ` <lastmod>${ p.modified.slice( 0, 10 ) }</lastmod>` ] : [] ), ...alts, ' </url>' ].join( '\n' ) );
458
+ }
459
+ }
460
+ await writeFile(
461
+ join( root, 'sitemap.xml' ),
462
+ `<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">\n${ urls.join( '\n' ) }\n</urlset>\n`
463
+ );
464
+ }
465
+
466
+ options.logger?.info( `${ pages.length } pages in Markdown, llms.txt and llms-full.txt${ locales.length > 1 ? ' (' + locales.join( ', ' ) + ')' : '' }${ options.sitemap === false ? '' : ', sitemap.xml' }` );
467
+ return { pages: pages.length };
468
+ }
469
+
470
+ /**
471
+ * Intégration Astro : buildAiFiles() à la fin du build, avec l'adresse `site` de la configuration.
472
+ *
473
+ * @param {Omit<Parameters<typeof buildAiFiles>[0], 'dir'|'site'> & {site?:string}} [options]
474
+ */
475
+ export function aiReady( options = {} ) {
476
+ let site = options.site || '';
477
+ return {
478
+ name: 'leiho-ai-ready',
479
+ hooks: {
480
+ 'astro:config:done': ( { config } ) => {
481
+ site = site || config.site || '';
482
+ },
483
+ 'astro:build:done': async ( { dir, logger } ) => {
484
+ await buildAiFiles( { ...options, dir, site, logger } );
485
+ },
486
+ },
487
+ };
488
+ }
package/src/content.js CHANGED
@@ -43,6 +43,8 @@ export function exportUrl( url ) {
43
43
  * @param {object} [options]
44
44
  * @param {string} [options.url] Adresse du CMS. Défaut : process.env.LEIHO_URL.
45
45
  * @param {string} [options.token] Jeton (accès restreint). Défaut : process.env.LEIHO_TOKEN.
46
+ * @param {string} [options.locale] Langue (Collections traduites) : contenu traduit, repli sur la
47
+ * langue par défaut, chemins préfixés (/fr/…). Défaut : langue par défaut.
46
48
  * @param {string|false} [options.snapshot] Fichier d'instantané, false pour s'en passer.
47
49
  * @param {'snapshot'|'error'} [options.fallback] Si WordPress ne répond pas : instantané (défaut) ou échec.
48
50
  * @param {number} [options.retries] Tentatives (défaut 3).
@@ -54,9 +56,12 @@ export function exportUrl( url ) {
54
56
  export async function loadLeihoContent( options = {} ) {
55
57
  const env = typeof process !== 'undefined' ? process.env : {};
56
58
  // OKNO_URL / OKNO_TOKEN : noms d'avant le renommage en Leiho, encore lus.
57
- const url = exportUrl( options.url || env.LEIHO_URL || env.OKNO_URL );
59
+ const locale = options.locale ? String( options.locale ) : '';
60
+ const base = exportUrl( options.url || env.LEIHO_URL || env.OKNO_URL );
61
+ const url = locale ? base + ( base.includes( '?' ) ? '&' : '?' ) + 'locale=' + encodeURIComponent( locale ) : base;
58
62
  const token = options.token ?? env.LEIHO_TOKEN ?? env.OKNO_TOKEN ?? '';
59
- const snapshotPath = options.snapshot === false ? null : options.snapshot || DEFAULT_SNAPSHOT;
63
+ // Un instantané par langue : .leiho/content.fr.json.
64
+ const snapshotPath = options.snapshot === false ? null : options.snapshot || ( locale ? DEFAULT_SNAPSHOT.replace( /\.json$/, '.' + locale + '.json' ) : DEFAULT_SNAPSHOT );
60
65
  const fallback = options.fallback || 'snapshot';
61
66
  const retries = Math.max( 1, options.retries ?? 3 );
62
67
  const timeout = options.timeout ?? 30000;
@@ -64,9 +69,13 @@ export async function loadLeihoContent( options = {} ) {
64
69
  const logger = options.logger || console;
65
70
 
66
71
  // Instantané d'avant le renommage (.okno/) : repris tant qu'aucun .leiho/ n'existe.
67
- const snapshot = snapshotPath
72
+ let snapshot = snapshotPath
68
73
  ? ( await readSnapshot( snapshotPath ) ) ?? ( snapshotPath === DEFAULT_SNAPSHOT ? await readSnapshot( LEGACY_SNAPSHOT ) : null )
69
74
  : null;
75
+ // Instantané d'une autre langue (chemin choisi à la main) : pas réutilisable.
76
+ if ( snapshot && ( snapshot.locale || '' ) !== locale ) {
77
+ snapshot = null;
78
+ }
70
79
 
71
80
  const headers = { Accept: 'application/json' };
72
81
  if ( token ) {
@@ -99,6 +108,9 @@ export async function loadLeihoContent( options = {} ) {
99
108
  if ( ! data || ! Array.isArray( data.items ) ) {
100
109
  throw new Error( 'Leiho: unexpected response from ' + url + ' (is Leiho 1.0.0-beta.6+ active?)' );
101
110
  }
111
+ if ( locale ) {
112
+ data.locale = locale;
113
+ }
102
114
  if ( snapshotPath ) {
103
115
  // Un serveur en lecture seule (serverless, à la requête) ne peut
104
116
  // pas écrire l'instantané : le contenu reçu reste bon, on le sert.
package/src/html.js ADDED
@@ -0,0 +1,212 @@
1
+ /**
2
+ * Lecture d'HTML rendu (pages d'un build) en arbre, sans dépendance. Pensé pour
3
+ * le HTML produit par un framework, bien formé : balises vides, texte brut
4
+ * (script, style), fermetures implicites courantes (p, li), entités.
5
+ *
6
+ * Nœuds : { type: 'element', tag, attrs, children } | { type: 'text', value }.
7
+ */
8
+
9
+ const VOID = new Set( [ 'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'source', 'track', 'wbr' ] );
10
+ const RAW = new Set( [ 'script', 'style', 'textarea', 'title' ] );
11
+ // Un de ces éléments ferme un <p> resté ouvert.
12
+ const CLOSES_P = new Set( [ 'address', 'article', 'aside', 'blockquote', 'details', 'div', 'dl', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'hr', 'main', 'nav', 'ol', 'p', 'pre', 'section', 'table', 'ul' ] );
13
+
14
+ const NAMED = {
15
+ amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: ' ', hellip: '…', mdash: '—', ndash: '–',
16
+ rsquo: '’', lsquo: '‘', rdquo: '”', ldquo: '“', laquo: '«', raquo: '»', copy: '©', reg: '®', trade: '™',
17
+ rarr: '→', larr: '←', times: '×', middot: '·', bull: '•', deg: '°', euro: '€', shy: '',
18
+ };
19
+
20
+ /**
21
+ * @param {string} text
22
+ * @returns {string}
23
+ */
24
+ export function decodeEntities( text ) {
25
+ return text.replace( /&(#x[0-9a-f]+|#[0-9]+|[a-z]+);/gi, ( match, code ) => {
26
+ if ( code[ 0 ] === '#' ) {
27
+ const n = code[ 1 ] === 'x' || code[ 1 ] === 'X' ? parseInt( code.slice( 2 ), 16 ) : parseInt( code.slice( 1 ), 10 );
28
+ return Number.isFinite( n ) ? String.fromCodePoint( n ) : match;
29
+ }
30
+ const value = NAMED[ code.toLowerCase() ];
31
+ return value === undefined ? match : value;
32
+ } );
33
+ }
34
+
35
+ const TAG = /<(\/?)([a-zA-Z][\w:-]*)((?:\s+[^\s"'>/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'=<>`]+))?)*)\s*(\/?)>/y;
36
+ const ATTR = /([^\s"'>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g;
37
+
38
+ function attributes( source ) {
39
+ const attrs = {};
40
+ for ( const m of source.matchAll( ATTR ) ) {
41
+ attrs[ m[ 1 ].toLowerCase() ] = decodeEntities( m[ 2 ] ?? m[ 3 ] ?? m[ 4 ] ?? '' );
42
+ }
43
+ return attrs;
44
+ }
45
+
46
+ /**
47
+ * @param {string} html
48
+ * @returns {{type:'root', children: any[]}}
49
+ */
50
+ export function parseHtml( html ) {
51
+ const root = { type: 'root', children: [] };
52
+ const stack = [ root ];
53
+ const top = () => stack[ stack.length - 1 ];
54
+ const close = ( tag ) => {
55
+ for ( let i = stack.length - 1; i > 0; i-- ) {
56
+ if ( stack[ i ].tag === tag ) {
57
+ stack.length = i;
58
+ return;
59
+ }
60
+ }
61
+ };
62
+ let i = 0;
63
+ let text = '';
64
+ const flush = () => {
65
+ if ( text ) {
66
+ top().children.push( { type: 'text', value: decodeEntities( text ) } );
67
+ text = '';
68
+ }
69
+ };
70
+
71
+ while ( i < html.length ) {
72
+ const lt = html.indexOf( '<', i );
73
+ if ( lt === -1 ) {
74
+ text += html.slice( i );
75
+ break;
76
+ }
77
+ text += html.slice( i, lt );
78
+ i = lt;
79
+
80
+ if ( html.startsWith( '<!--', i ) ) {
81
+ const end = html.indexOf( '-->', i + 4 );
82
+ i = end === -1 ? html.length : end + 3;
83
+ continue;
84
+ }
85
+ if ( html[ i + 1 ] === '!' || html[ i + 1 ] === '?' ) {
86
+ const end = html.indexOf( '>', i );
87
+ i = end === -1 ? html.length : end + 1;
88
+ continue;
89
+ }
90
+
91
+ TAG.lastIndex = i;
92
+ const m = TAG.exec( html );
93
+ if ( ! m ) {
94
+ text += '<';
95
+ i++;
96
+ continue;
97
+ }
98
+ flush();
99
+ i = TAG.lastIndex;
100
+ const tag = m[ 2 ].toLowerCase();
101
+
102
+ if ( m[ 1 ] ) {
103
+ close( tag );
104
+ continue;
105
+ }
106
+
107
+ if ( CLOSES_P.has( tag ) && top().tag === 'p' ) {
108
+ stack.pop();
109
+ }
110
+ if ( tag === 'li' ) {
111
+ closeSibling( stack, 'li', [ 'ul', 'ol' ] );
112
+ }
113
+ if ( tag === 'dt' || tag === 'dd' ) {
114
+ closeSibling( stack, tag === 'dt' ? 'dd' : 'dt', [ 'dl' ] );
115
+ closeSibling( stack, tag, [ 'dl' ] );
116
+ }
117
+ if ( tag === 'tr' || tag === 'td' || tag === 'th' ) {
118
+ if ( tag === 'tr' ) {
119
+ closeSibling( stack, 'tr', [ 'table', 'thead', 'tbody', 'tfoot' ] );
120
+ } else {
121
+ closeSibling( stack, 'td', [ 'tr' ] );
122
+ closeSibling( stack, 'th', [ 'tr' ] );
123
+ }
124
+ }
125
+
126
+ const node = { type: 'element', tag, attrs: attributes( m[ 3 ] ), children: [] };
127
+ top().children.push( node );
128
+
129
+ if ( RAW.has( tag ) ) {
130
+ const end = html.toLowerCase().indexOf( '</' + tag, i );
131
+ const raw = html.slice( i, end === -1 ? html.length : end );
132
+ if ( raw ) {
133
+ node.children.push( { type: 'text', value: tag === 'script' || tag === 'style' ? raw : decodeEntities( raw ) } );
134
+ }
135
+ const gt = end === -1 ? -1 : html.indexOf( '>', end );
136
+ i = gt === -1 ? html.length : gt + 1;
137
+ continue;
138
+ }
139
+ if ( ! VOID.has( tag ) && ! m[ 4 ] ) {
140
+ stack.push( node );
141
+ }
142
+ }
143
+ flush();
144
+ return root;
145
+ }
146
+
147
+ // Ferme un frère resté ouvert (<li> sans </li>), sans remonter au-delà de son conteneur.
148
+ function closeSibling( stack, tag, containers ) {
149
+ for ( let i = stack.length - 1; i > 0; i-- ) {
150
+ if ( containers.includes( stack[ i ].tag ) ) {
151
+ return;
152
+ }
153
+ if ( stack[ i ].tag === tag ) {
154
+ stack.length = i;
155
+ return;
156
+ }
157
+ }
158
+ }
159
+
160
+ /**
161
+ * Texte d'un nœud et de ses descendants.
162
+ *
163
+ * @param {any} node
164
+ * @returns {string}
165
+ */
166
+ export function textOf( node ) {
167
+ if ( node.type === 'text' ) {
168
+ return node.value;
169
+ }
170
+ if ( node.type === 'element' && node.tag === 'br' ) {
171
+ return '\n';
172
+ }
173
+ return ( node.children || [] ).map( textOf ).join( '' );
174
+ }
175
+
176
+ /**
177
+ * Premier nœud qui satisfait le test (parcours en profondeur).
178
+ *
179
+ * @param {any} node
180
+ * @param {(n:any)=>boolean} test
181
+ * @returns {any|null}
182
+ */
183
+ export function findNode( node, test ) {
184
+ if ( test( node ) ) {
185
+ return node;
186
+ }
187
+ for ( const child of node.children || [] ) {
188
+ const hit = findNode( child, test );
189
+ if ( hit ) {
190
+ return hit;
191
+ }
192
+ }
193
+ return null;
194
+ }
195
+
196
+ /**
197
+ * Tous les nœuds qui satisfont le test.
198
+ *
199
+ * @param {any} node
200
+ * @param {(n:any)=>boolean} test
201
+ * @param {any[]} [out]
202
+ * @returns {any[]}
203
+ */
204
+ export function findNodes( node, test, out = [] ) {
205
+ if ( test( node ) ) {
206
+ out.push( node );
207
+ }
208
+ for ( const child of node.children || [] ) {
209
+ findNodes( child, test, out );
210
+ }
211
+ return out;
212
+ }
package/src/index.js CHANGED
@@ -275,22 +275,68 @@ export function initLeihoBridge( options ) {
275
275
  * Application des valeurs
276
276
  * ------------------------------------------------------------------ */
277
277
 
278
+ // Liste blanche : seul ce qu'un texte riche contient passe. Une liste noire
279
+ // laisse toujours une porte (noscript, svg/math, schémas d'URL exotiques).
280
+ const ALLOWED_TAGS = new Set( [
281
+ 'A', 'ABBR', 'B', 'BLOCKQUOTE', 'BR', 'CAPTION', 'CITE', 'CODE', 'DD', 'DEL', 'DIV', 'DL', 'DT', 'EM', 'FIGCAPTION',
282
+ 'FIGURE', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'HR', 'I', 'IMG', 'INS', 'KBD', 'LI', 'MARK', 'OL', 'P', 'PRE', 'Q',
283
+ 'S', 'SMALL', 'SPAN', 'STRONG', 'SUB', 'SUP', 'TABLE', 'TBODY', 'TD', 'TFOOT', 'TH', 'THEAD', 'TR', 'U', 'UL',
284
+ ] );
285
+ // Hors liste blanche et retirées avec leur contenu (code, documents imbriqués).
286
+ const DROPPED_TAGS = new Set( [ ...BANNED_TAGS.map( ( t ) => t.toUpperCase() ), 'NOSCRIPT', 'NOEMBED', 'NOFRAMES', 'TEMPLATE', 'SVG', 'MATH', 'XMP', 'TEXTAREA', 'TITLE', 'SELECT', 'OBJECT' ] );
287
+ const ALLOWED_ATTRS = new Set( [ 'href', 'src', 'alt', 'title', 'class', 'width', 'height', 'target', 'rel', 'colspan', 'rowspan', 'lang', 'dir', 'start', 'reversed', 'loading', 'decoding', 'srcset', 'sizes', 'id', 'style' ] );
288
+
289
+ /** Adresse sûre : http(s), mailto, tel ou relative. */
290
+ function safeUrl( value ) {
291
+ const url = String( null == value ? '' : value ).replace( /[\u0000-\u0020\u007f-\u009f]/g, '' );
292
+ const scheme = url.match( /^([a-z][a-z0-9+.-]*):/i );
293
+ return ! scheme || /^(https?|mailto|tel)$/i.test( scheme[ 1 ] ) ? String( value ) : '';
294
+ }
295
+
278
296
  function sanitizeHtml( html ) {
279
- const doc = document.implementation.createHTMLDocument( '' );
280
- doc.body.innerHTML = String( null == html ? '' : html );
281
- doc.body.querySelectorAll( BANNED_TAGS.join( ',' ) ).forEach( ( el ) => el.remove() );
282
- doc.body.querySelectorAll( '*' ).forEach( ( el ) => {
283
- [ ...el.attributes ].forEach( ( attr ) => {
284
- const name = attr.name.toLowerCase();
285
- const value = attr.value.replace( /\s+/g, '' ).toLowerCase();
286
- if ( 0 === name.indexOf( 'on' ) ) {
287
- el.removeAttribute( attr.name );
288
- } else if ( ( 'href' === name || 'src' === name || 'xlink:href' === name ) && 0 === value.indexOf( 'javascript:' ) ) {
289
- el.removeAttribute( attr.name );
297
+ const source = new DOMParser().parseFromString( '<body>' + String( null == html ? '' : html ) + '</body>', 'text/html' ).body;
298
+ const clean = ( node, into ) => {
299
+ node.childNodes.forEach( ( child ) => {
300
+ if ( child.nodeType === Node.TEXT_NODE ) {
301
+ into.appendChild( document.createTextNode( child.nodeValue ) );
302
+ return;
303
+ }
304
+ if ( child.nodeType !== Node.ELEMENT_NODE ) {
305
+ return;
306
+ }
307
+ if ( ! ALLOWED_TAGS.has( child.tagName ) ) {
308
+ // Balise inconnue : son texte reste, sauf pour ce qui n'en a pas à montrer.
309
+ if ( ! DROPPED_TAGS.has( child.tagName.toUpperCase() ) ) {
310
+ clean( child, into );
311
+ }
312
+ return;
290
313
  }
314
+ const el = document.createElement( child.tagName );
315
+ [ ...child.attributes ].forEach( ( a ) => {
316
+ const name = a.name.toLowerCase();
317
+ if ( ! ALLOWED_ATTRS.has( name ) ) {
318
+ return;
319
+ }
320
+ if ( 'href' === name || 'src' === name ) {
321
+ const url = safeUrl( a.value );
322
+ if ( url ) {
323
+ el.setAttribute( name, url );
324
+ }
325
+ } else if ( 'srcset' === name ) {
326
+ if ( ! /(^|,)\s*[a-z][a-z0-9+.-]*:/i.test( a.value ) || a.value.split( ',' ).every( ( part ) => safeUrl( part.trim().split( /\s+/ )[ 0 ] ) ) ) {
327
+ el.setAttribute( name, a.value );
328
+ }
329
+ } else {
330
+ el.setAttribute( name, a.value );
331
+ }
332
+ } );
333
+ clean( child, el );
334
+ into.appendChild( el );
291
335
  } );
292
- } );
293
- return doc.body.innerHTML;
336
+ };
337
+ const out = document.createElement( 'div' );
338
+ clean( source, out );
339
+ return out.innerHTML;
294
340
  }
295
341
 
296
342
  /**
@@ -313,12 +359,13 @@ export function initLeihoBridge( options ) {
313
359
  if ( 'image' === fieldType ) {
314
360
  const img = 'IMG' === el.tagName ? el : el.querySelector( 'img' );
315
361
  if ( img ) {
316
- if ( img.getAttribute( 'src' ) !== ( value || '' ) ) {
317
- img.setAttribute( 'src', value || '' );
362
+ if ( img.getAttribute( 'src' ) !== safeUrl( value || '' ) ) {
363
+ img.setAttribute( 'src', safeUrl( value || '' ) );
318
364
  img.removeAttribute( 'srcset' );
319
365
  }
320
366
  } else {
321
- el.style.backgroundImage = value ? 'url("' + value + '")' : '';
367
+ const src = safeUrl( value || '' );
368
+ el.style.backgroundImage = src ? 'url("' + src.replace( /["\\\n]/g, '' ) + '")' : '';
322
369
  }
323
370
  } else if ( 'color_picker' === fieldType ) {
324
371
  el.style.setProperty( attr( el, 'style' ) || 'color', value || '' );
@@ -326,7 +373,7 @@ export function initLeihoBridge( options ) {
326
373
  const link = 'A' === el.tagName ? el : el.querySelector( 'a' );
327
374
  const data = value && 'object' === typeof value ? value : { url: value };
328
375
  if ( link ) {
329
- link.setAttribute( 'href', data.url || '' );
376
+ link.setAttribute( 'href', safeUrl( data.url || '' ) );
330
377
  if ( data.target ) {
331
378
  link.setAttribute( 'target', data.target );
332
379
  } else {
@@ -488,6 +535,9 @@ export function initLeihoBridge( options ) {
488
535
  } catch ( e ) {
489
536
  return;
490
537
  }
538
+ if ( ! /^https?:$/.test( url.protocol ) ) {
539
+ return;
540
+ }
491
541
  send( { type: 'navigate', href: url.href, path: url.pathname, external: url.origin !== window.location.origin } );
492
542
  return;
493
543
  }
@@ -527,7 +577,7 @@ export function initLeihoBridge( options ) {
527
577
  }
528
578
 
529
579
  window.addEventListener( 'message', ( event ) => {
530
- if ( event.origin !== wpOrigin || ! event.data || event.data.ns !== NS ) {
580
+ if ( event.origin !== wpOrigin || event.source !== window.parent || ! event.data || event.data.ns !== NS ) {
531
581
  return;
532
582
  }
533
583
  const data = event.data;
package/src/seo.js ADDED
@@ -0,0 +1,196 @@
1
+ /**
2
+ * Données structurées schema.org d'une page, en un seul graphe JSON-LD.
3
+ *
4
+ * import { leihoGraph, jsonLd } from 'leiho/seo';
5
+ *
6
+ * const graph = leihoGraph( {
7
+ * url: 'https://example.com/docs/install',
8
+ * item, // contenu Leiho : item.seo.jsonld (page, article, FAQ)
9
+ * site: { url: 'https://example.com', name: 'Example', locales: [ 'en', 'fr' ] },
10
+ * organization: { name: 'Example Inc.', url: 'https://example.com', logo: 'https://example.com/logo.png' },
11
+ * breadcrumbs: [ { name: 'Docs', url: '/docs' }, { name: 'Install' } ],
12
+ * } );
13
+ * // <script type="application/ld+json">{ jsonLd( graph ) }</script>
14
+ *
15
+ * Le plugin calcule les nœuds propres au contenu (type déclaré dans la
16
+ * collection, description, image, FAQ, dates, langue) ; ce module y ajoute le
17
+ * site, l'organisation et le fil d'Ariane, reliés par des @id stables.
18
+ */
19
+
20
+ const clean = ( value ) => {
21
+ if ( Array.isArray( value ) ) {
22
+ const list = value.map( clean ).filter( ( v ) => v !== undefined );
23
+ return list.length ? list : undefined;
24
+ }
25
+ if ( value && typeof value === 'object' ) {
26
+ const out = {};
27
+ for ( const [ k, v ] of Object.entries( value ) ) {
28
+ const c = clean( v );
29
+ if ( c !== undefined ) {
30
+ out[ k ] = c;
31
+ }
32
+ }
33
+ return Object.keys( out ).length ? out : undefined;
34
+ }
35
+ return value === null || value === '' ? undefined : value;
36
+ };
37
+
38
+ const absolute = ( href, origin ) => {
39
+ if ( ! href ) {
40
+ return undefined;
41
+ }
42
+ return /^https?:/i.test( href ) ? href : origin + ( href.startsWith( '/' ) ? href : '/' + href );
43
+ };
44
+
45
+ /**
46
+ * @param {object} input
47
+ * @param {string} input.url Adresse canonique de la page.
48
+ * @param {object} [input.item] Contenu Leiho (item.seo.jsonld).
49
+ * @param {{url:string, name:string, description?:string, locales?:string[]}} input.site
50
+ * @param {{name:string, url?:string, logo?:string, sameAs?:string[]}} [input.organization]
51
+ * @param {string} [input.title] Nom de la page (sans item, ou pour le remplacer).
52
+ * @param {string} [input.description]
53
+ * @param {string} [input.locale]
54
+ * @param {string} [input.modified] Date ISO.
55
+ * @param {string} [input.published] Date ISO.
56
+ * @param {string} [input.type] Type de la page sans item (WebPage, AboutPage…).
57
+ * @param {{name:string, url?:string}[]} [input.breadcrumbs] Fil d'Ariane, accueil exclu : il est ajouté.
58
+ * @param {object[]} [input.nodes] Nœuds en plus (produit, logiciel, événement…).
59
+ * @returns {{'@context':string, '@graph':object[]}}
60
+ */
61
+ export function leihoGraph( input ) {
62
+ const siteUrl = String( input.site.url ).replace( /\/+$/, '' );
63
+ const url = absolute( input.url, siteUrl );
64
+ const websiteId = siteUrl + '/#website';
65
+ const orgId = siteUrl + '/#organization';
66
+ const pageId = url + '#webpage';
67
+ const graph = [];
68
+
69
+ if ( input.organization ) {
70
+ const o = input.organization;
71
+ graph.push( {
72
+ '@type': 'Organization',
73
+ '@id': orgId,
74
+ name: o.name,
75
+ url: o.url,
76
+ logo: o.logo ? { '@type': 'ImageObject', url: absolute( o.logo, siteUrl ) } : undefined,
77
+ sameAs: o.sameAs,
78
+ } );
79
+ }
80
+
81
+ graph.push( {
82
+ '@type': 'WebSite',
83
+ '@id': websiteId,
84
+ url: siteUrl,
85
+ name: input.site.name,
86
+ description: input.site.description,
87
+ inLanguage: input.site.locales,
88
+ publisher: input.organization ? { '@id': orgId } : undefined,
89
+ } );
90
+
91
+ const crumbs = input.breadcrumbs || [];
92
+ const fromItem = input.item?.seo?.jsonld || [];
93
+ const page = fromItem.find( ( n ) => n[ '@id' ] === pageId ) || fromItem[ 0 ];
94
+ const shared = {
95
+ isPartOf: { '@id': websiteId },
96
+ publisher: input.organization ? { '@id': orgId } : undefined,
97
+ breadcrumb: crumbs.length ? { '@id': url + '#breadcrumb' } : undefined,
98
+ };
99
+
100
+ if ( page ) {
101
+ // Nœuds du plugin : la page prend l'adresse canonique donnée ici (le
102
+ // front peut servir l'entrée sous une autre adresse que celle du CMS).
103
+ const itemUrl = page.url;
104
+ const relink = ( node ) =>
105
+ JSON.parse( JSON.stringify( node ), ( k, v ) => {
106
+ if ( typeof v !== 'string' || ! itemUrl ) {
107
+ return v;
108
+ }
109
+ if ( v === itemUrl ) {
110
+ return url;
111
+ }
112
+ return v.startsWith( itemUrl + '#' ) ? url + v.slice( itemUrl.length ) : v;
113
+ } );
114
+ for ( const node of fromItem ) {
115
+ const copy = relink( node );
116
+ if ( node === page ) {
117
+ Object.assign( copy, shared, input.title ? { name: input.title } : {}, input.description ? { description: input.description } : {} );
118
+ }
119
+ if ( input.organization && copy[ '@type' ] && /Article|Posting/.test( copy[ '@type' ] ) ) {
120
+ copy.publisher = { '@id': orgId };
121
+ copy.author = copy.author || { '@id': orgId };
122
+ }
123
+ graph.push( copy );
124
+ }
125
+ } else {
126
+ graph.push( {
127
+ '@type': input.type || 'WebPage',
128
+ '@id': pageId,
129
+ url,
130
+ name: input.title,
131
+ description: input.description,
132
+ inLanguage: input.locale,
133
+ datePublished: input.published,
134
+ dateModified: input.modified,
135
+ ...shared,
136
+ } );
137
+ }
138
+
139
+ if ( crumbs.length ) {
140
+ const list = [ { name: input.site.name, url: siteUrl }, ...crumbs ];
141
+ graph.push( {
142
+ '@type': 'BreadcrumbList',
143
+ '@id': url + '#breadcrumb',
144
+ itemListElement: list.map( ( c, i ) => ( {
145
+ '@type': 'ListItem',
146
+ position: i + 1,
147
+ name: c.name,
148
+ item: i === list.length - 1 ? url : absolute( c.url, siteUrl ),
149
+ } ) ),
150
+ } );
151
+ }
152
+
153
+ graph.push( ...( input.nodes || [] ) );
154
+ return { '@context': 'https://schema.org', '@graph': clean( graph ) };
155
+ }
156
+
157
+ /**
158
+ * JSON sûr dans une balise <script type="application/ld+json"> (pas de </script> possible).
159
+ *
160
+ * @param {unknown} data
161
+ * @returns {string}
162
+ */
163
+ export function jsonLd( data ) {
164
+ return JSON.stringify( data ).replace( /</g, '\\u003c' ).replace( /\u2028/g, '\\u2028' ).replace( /\u2029/g, '\\u2029' );
165
+ }
166
+
167
+ /**
168
+ * Balises <head> d'une page tirées de item.seo : titre, description, Open Graph.
169
+ * Renvoie des objets à rendre avec le framework (pas de HTML à échapper).
170
+ *
171
+ * @param {object} item Contenu Leiho.
172
+ * @param {object} [options]
173
+ * @param {string} [options.url] Adresse canonique.
174
+ * @param {string} [options.siteName]
175
+ * @returns {{title:string, description:string, image?:string, meta: {name?:string, property?:string, content:string}[]}}
176
+ */
177
+ export function seoMeta( item, options = {} ) {
178
+ const seo = item?.seo || {};
179
+ const title = seo.title || item?.title || '';
180
+ const description = seo.description || '';
181
+ const image = seo.image?.url;
182
+ const isArticle = /Article|Posting/.test( seo.type || '' );
183
+ const meta = [
184
+ description && { name: 'description', content: description },
185
+ { property: 'og:type', content: isArticle ? 'article' : 'website' },
186
+ { property: 'og:title', content: title },
187
+ description && { property: 'og:description', content: description },
188
+ options.url && { property: 'og:url', content: options.url },
189
+ options.siteName && { property: 'og:site_name', content: options.siteName },
190
+ image && { property: 'og:image', content: image },
191
+ image && seo.image?.alt && { property: 'og:image:alt', content: seo.image.alt },
192
+ { name: 'twitter:card', content: image ? 'summary_large_image' : 'summary' },
193
+ item?.modified && { property: 'article:modified_time', content: item.modified },
194
+ ].filter( Boolean );
195
+ return { title, description, image, meta };
196
+ }