@po-ui/ng-code-editor 19.39.28 → 19.39.29

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.
@@ -1,8 +1,205 @@
1
1
  import * as i0 from '@angular/core';
2
- import { Directive, Input, Injectable, forwardRef, Component, ViewChild, NgModule } from '@angular/core';
2
+ import { Directive, Input, Injectable, forwardRef, inject, CSP_NONCE, Component, ViewChild, NgModule } from '@angular/core';
3
3
  import { NG_VALUE_ACCESSOR } from '@angular/forms';
4
4
  import { CommonModule } from '@angular/common';
5
5
 
6
+ /**
7
+ * @docsPrivate
8
+ *
9
+ * Camada de compatibilidade entre o Monaco Editor (`0.44.0`) e Content-Security-Policy (CSP) baseada em *nonce*.
10
+ *
11
+ * O Monaco não oferece opção de *nonce* para os estilos que cria em tempo de execução. Sem esta camada, uma política
12
+ * sem `'unsafe-inline'` bloqueia:
13
+ *
14
+ * 1. os elementos `<style>` criados pelo Monaco (`document.createElement('style')`, inclusive no *shadow DOM* do menu
15
+ * de contexto). **Correção:** o *nonce* é aplicado somente nos `<style>` criados por código do Monaco;
16
+ * 2. os atributos `style` do HTML que o Monaco monta como texto (linhas, números de linha, seleção, decorações etc.).
17
+ * O *nonce* não se aplica a atributos. **Correção:** o HTML passa pelo *hook* público
18
+ * `MonacoEnvironment.createTrustedTypesPolicy`; o atributo `style` das tags é renomeado para um atributo de marcação e,
19
+ * logo após a inserção no DOM (na mesma tarefa), o valor é aplicado via CSSOM (`element.style.cssText`), que a CSP não
20
+ * bloqueia;
21
+ * 3. o `setAttribute('style', ...)` usado pelo Monaco (indicadores do modo diff). **Correção:** quando a chamada vem
22
+ * do Monaco, o valor é aplicado via CSSOM.
23
+ *
24
+ * Escopo:
25
+ * - A camada só é instalada quando a aplicação informa o `CSP_NONCE`, uma vez por página, antes do carregamento do
26
+ * Monaco.
27
+ * - Apenas o HTML produzido pelas políticas de Trusted Types do Monaco é convertido. O Monaco escapa `<`, `>` e `&` no
28
+ * conteúdo do usuário, então o conteúdo não consegue criar tags nem atributos. As demais atribuições de `innerHTML`
29
+ * da página não são alteradas.
30
+ * - Chamadas de `createElement` e `setAttribute` só são alteradas quando o código do Monaco está na pilha de chamadas
31
+ * (identificado pela URL da pasta `vs` do Monaco). Se essa identificação falhar, o comportamento é o anterior.
32
+ */
33
+ /** Atributo de marcação que substitui o `style` no HTML gerado pelo Monaco até a aplicação via CSSOM. */
34
+ const PO_CSP_STYLE_MARKER = 'data-po-csp-style';
35
+ const INSTALLED_KEY = '__poCodeEditorCspCompat';
36
+ /**
37
+ * Tags do HTML gerado pelo Monaco. Como o Monaco escapa `<` e `>` no conteúdo, cada trecho `<...>` é uma tag.
38
+ */
39
+ const TAG_REGEX = /<[a-zA-Z][^<>]*>/g;
40
+ /** Atributo `style` dentro de uma tag (precedido de espaço, para não alcançar, por exemplo, `data-style`). */
41
+ const STYLE_ATTRIBUTE_REGEX = /(\s)style=(["'])/g;
42
+ /** HTML gerado pelo Monaco quando o navegador não oferece Trusted Types. É convertido em texto pelo navegador. */
43
+ class PoCspMarkedHtml {
44
+ html;
45
+ constructor(html) {
46
+ this.html = html;
47
+ }
48
+ toString() {
49
+ return this.html;
50
+ }
51
+ }
52
+ /**
53
+ * Renomeia o atributo `style` das tags do HTML para o atributo de marcação. O conteúdo de texto não é alterado.
54
+ */
55
+ function rewriteStyleAttributes(html) {
56
+ if (typeof html !== 'string' || !html.includes('style=')) {
57
+ return html;
58
+ }
59
+ return html.replaceAll(TAG_REGEX, tag => tag.replaceAll(STYLE_ATTRIBUTE_REGEX, `$1${PO_CSP_STYLE_MARKER}=$2`));
60
+ }
61
+ /**
62
+ * Aplica via CSSOM os estilos marcados no elemento e nos seus descendentes e remove o atributo de marcação.
63
+ */
64
+ function applyMarkedStyles(root) {
65
+ if (!root) {
66
+ return;
67
+ }
68
+ if (root.hasAttribute(PO_CSP_STYLE_MARKER)) {
69
+ applyMarkedStyle(root);
70
+ }
71
+ root.querySelectorAll(`[${PO_CSP_STYLE_MARKER}]`).forEach(applyMarkedStyle);
72
+ }
73
+ /**
74
+ * Instala a camada de compatibilidade. A instalação é única por página: chamadas seguintes reaproveitam a primeira.
75
+ *
76
+ * @returns Função que desfaz a instalação (usada nos testes).
77
+ */
78
+ function installMonacoCspCompat(options) {
79
+ const win = globalThis;
80
+ if (win[INSTALLED_KEY]) {
81
+ return win[INSTALLED_KEY].dispose;
82
+ }
83
+ const { nonce, monacoBaseUrl } = options;
84
+ const producedHtml = new WeakSet();
85
+ const isProducedHtml = (value) => value !== null && typeof value === 'object' && producedHtml.has(value);
86
+ const isCalledFromMonaco = () => {
87
+ const stack = new Error('po-code-editor-csp-compat: call origin').stack;
88
+ return !!stack && stack.includes(monacoBaseUrl);
89
+ };
90
+ const markHtml = (html) => {
91
+ if (typeof html === 'string') {
92
+ const marked = new PoCspMarkedHtml(html);
93
+ producedHtml.add(marked);
94
+ return marked;
95
+ }
96
+ if (html !== null && typeof html === 'object') {
97
+ producedHtml.add(html);
98
+ }
99
+ return html;
100
+ };
101
+ // 1) <style> criados pelo Monaco recebem o nonce.
102
+ const originalCreateElement = Document.prototype.createElement;
103
+ Document.prototype.createElement = function (tagName, elementOptions) {
104
+ const element = originalCreateElement.call(this, tagName, elementOptions);
105
+ if (isStyleTag(tagName) && !element.nonce && isCalledFromMonaco()) {
106
+ element.setAttribute('nonce', nonce);
107
+ }
108
+ return element;
109
+ };
110
+ // 2) setAttribute('style', ...) do Monaco passa a ser aplicado via CSSOM.
111
+ const originalSetAttribute = Element.prototype.setAttribute;
112
+ Element.prototype.setAttribute = function (name, value) {
113
+ if (name === 'style' && this.style && isCalledFromMonaco()) {
114
+ this.style.cssText = String(value);
115
+ return;
116
+ }
117
+ return originalSetAttribute.call(this, name, value);
118
+ };
119
+ // 3) HTML gerado pelo Monaco: o atributo style é marcado na criação do HTML...
120
+ const environment = (win.MonacoEnvironment = win.MonacoEnvironment || {});
121
+ const previousPolicyFactory = environment.createTrustedTypesPolicy;
122
+ const createPolicy = (name, policyOptions) => previousPolicyFactory
123
+ ? previousPolicyFactory.call(environment, name, policyOptions)
124
+ : win.trustedTypes?.createPolicy?.(name, policyOptions);
125
+ environment.createTrustedTypesPolicy = (name, policyOptions) => {
126
+ if (!policyOptions || typeof policyOptions.createHTML !== 'function') {
127
+ return createPolicy(name, policyOptions);
128
+ }
129
+ const wrappedOptions = {
130
+ ...policyOptions,
131
+ createHTML: (input, ...args) => rewriteStyleAttributes(policyOptions.createHTML(input, ...args))
132
+ };
133
+ const policy = createPolicy(name, wrappedOptions);
134
+ if (!policy) {
135
+ // Navegador sem Trusted Types: o HTML marcado é convertido em texto pelo setter de innerHTML.
136
+ return {
137
+ name,
138
+ createHTML: (input, ...args) => markHtml(wrappedOptions.createHTML(input, ...args))
139
+ };
140
+ }
141
+ return {
142
+ name: policy.name ?? name,
143
+ createHTML: (input, ...args) => markHtml(policy.createHTML(input, ...args)),
144
+ createScript: policy.createScript?.bind(policy),
145
+ createScriptURL: policy.createScriptURL?.bind(policy)
146
+ };
147
+ };
148
+ // ... e aplicado via CSSOM logo após a inserção (mesma tarefa, antes das medições do Monaco).
149
+ const innerHTMLDescriptor = Object.getOwnPropertyDescriptor(Element.prototype, 'innerHTML');
150
+ if (innerHTMLDescriptor?.set) {
151
+ Object.defineProperty(Element.prototype, 'innerHTML', {
152
+ ...innerHTMLDescriptor,
153
+ set(value) {
154
+ innerHTMLDescriptor.set.call(this, value);
155
+ if (isProducedHtml(value)) {
156
+ applyMarkedStyles(this);
157
+ }
158
+ }
159
+ });
160
+ }
161
+ const originalInsertAdjacentHTML = Element.prototype.insertAdjacentHTML;
162
+ Element.prototype.insertAdjacentHTML = function (position, text) {
163
+ originalInsertAdjacentHTML.call(this, position, text);
164
+ if (isProducedHtml(text)) {
165
+ const insertsAsSibling = /^(beforebegin|afterend)$/i.test(String(position));
166
+ applyMarkedStyles(insertsAsSibling ? this.parentElement : this);
167
+ }
168
+ };
169
+ const dispose = () => {
170
+ Document.prototype.createElement = originalCreateElement;
171
+ Element.prototype.setAttribute = originalSetAttribute;
172
+ Element.prototype.insertAdjacentHTML = originalInsertAdjacentHTML;
173
+ if (innerHTMLDescriptor) {
174
+ Object.defineProperty(Element.prototype, 'innerHTML', innerHTMLDescriptor);
175
+ }
176
+ if (previousPolicyFactory) {
177
+ environment.createTrustedTypesPolicy = previousPolicyFactory;
178
+ }
179
+ else {
180
+ delete environment.createTrustedTypesPolicy;
181
+ }
182
+ delete win[INSTALLED_KEY];
183
+ };
184
+ win[INSTALLED_KEY] = { dispose };
185
+ return dispose;
186
+ }
187
+ /** Desfaz a instalação, se houver (usada nos testes). */
188
+ function disposeMonacoCspCompat() {
189
+ globalThis[INSTALLED_KEY]?.dispose();
190
+ }
191
+ function isStyleTag(tagName) {
192
+ return typeof tagName === 'string' && tagName.length === 5 && tagName.toLowerCase() === 'style';
193
+ }
194
+ function applyMarkedStyle(element) {
195
+ const css = element.getAttribute(PO_CSP_STYLE_MARKER) ?? '';
196
+ element.removeAttribute(PO_CSP_STYLE_MARKER);
197
+ const style = element.style;
198
+ if (style) {
199
+ style.cssText = css;
200
+ }
201
+ }
202
+
6
203
  const PO_CODE_EDITOR_THEMES = ['vs-dark', 'vs', 'hc-black'];
7
204
  const PO_CODE_EDITOR_THEME_DEFAULT = 'vs';
8
205
  /**
@@ -62,6 +259,53 @@ const PO_CODE_EDITOR_THEME_DEFAULT = 'vs';
62
259
  * ]
63
260
  * ...
64
261
  * </pre>
262
+ *
263
+ * #### Content Security Policy (CSP)
264
+ *
265
+ * O `po-code-editor` é compatível com políticas de segurança restritivas (CSP) baseadas em *nonce*, sem a necessidade
266
+ * de `'unsafe-inline'` em `script-src`, `style-src`, `style-src-elem` ou `style-src-attr`.
267
+ *
268
+ * O *nonce* é obtido do token `CSP_NONCE` do Angular, ou do atributo `ngCspNonce` em um elemento do `body`
269
+ * (normalmente o `<app-root>`). Não existe configuração específica do PO UI para isso e não é necessário chamar
270
+ * nenhum método ou informar nenhuma propriedade no componente.
271
+ *
272
+ * ```
273
+ * <!-- index.html -->
274
+ * <app-root ngCspNonce="NONCE_DA_REQUISICAO"></app-root>
275
+ * ```
276
+ *
277
+ * ou
278
+ *
279
+ * ```
280
+ * import { CSP_NONCE } from '@angular/core';
281
+ *
282
+ * providers: [{ provide: CSP_NONCE, useValue: nonceDaRequisicao }]
283
+ * ```
284
+ *
285
+ * Quando o *nonce* é informado, o `po-code-editor`:
286
+ *
287
+ * - aplica o *nonce* no `<script>` do `loader.js` do Monaco e o repassa à configuração do *loader* (`cspNonce`), que
288
+ * o aplica nos scripts que ele mesmo carrega;
289
+ * - aplica o *nonce* nos elementos `<style>` criados pelo Monaco, inclusive no *shadow DOM* do menu de contexto;
290
+ * - aplica, via CSSOM (`element.style`), os estilos que o Monaco define no atributo `style` dos elementos (posição das
291
+ * linhas, números de linha, seleção, decorações e indicadores do modo de comparação), pois o *nonce* não se aplica a
292
+ * atributos.
293
+ *
294
+ * Esses ajustes valem apenas para os elementos criados pelo Monaco e não alteram o restante da aplicação.
295
+ *
296
+ * **Pontos de atenção**
297
+ *
298
+ * - O valor informado deve ser o mesmo *nonce* enviado na política (`'nonce-...'`) da requisição atual.
299
+ * - O Monaco é carregado apenas uma vez por carregamento da página, quando o primeiro `po-code-editor` é exibido.
300
+ * Por isso, o *nonce* deve estar disponível antes disso.
301
+ * - O Monaco deve ser servido a partir de `assets/monaco/vs`, como configurado pelo `ng add @po-ui/ng-code-editor`.
302
+ * - Quando o *nonce* não é informado, o componente se comporta como antes: nenhum ajuste é aplicado.
303
+ * - A política também precisa permitir os demais recursos do Monaco (por exemplo, `worker-src` e `font-src`). Valide
304
+ * a política utilizada em um ambiente de teste antes de aplicá-la em produção.
305
+ *
306
+ * > **Atenção:** não utilize `'unsafe-inline'` em `style-src`, `style-src-elem` ou `style-src-attr` para contornar
307
+ * > bloqueios do editor. Quando a diretiva possui um *nonce*, o navegador ignora o `'unsafe-inline'`; e, caso o *nonce*
308
+ * > seja removido para que ele valha, qualquer estilo injetado passa a ser aceito, o que enfraquece a política.
65
309
  */
66
310
  class PoCodeEditorBaseComponent {
67
311
  editor;
@@ -413,6 +657,7 @@ class PoCodeEditorComponent extends PoCodeEditorBaseComponent {
413
657
  codeEditorRegister;
414
658
  editorContainer;
415
659
  canLoad = false;
660
+ cspNonce = inject(CSP_NONCE, { optional: true });
416
661
  constructor(zone, el, poCodeEditorSuggestionService, codeEditorRegister) {
417
662
  super();
418
663
  this.zone = zone;
@@ -439,32 +684,31 @@ class PoCodeEditorComponent extends PoCodeEditorBaseComponent {
439
684
  else {
440
685
  loadedMonaco = true;
441
686
  loadPromise = new Promise((resolve) => {
442
- /* istanbul ignore next */
443
- const onGotAmdLoader = () => {
444
- window.require.config({ paths: { 'vs': './assets/monaco/vs' } });
445
- window.require(['vs/editor/editor.main'], () => {
446
- setTimeout(() => {
447
- if (this.el.nativeElement.offsetWidth) {
448
- this.registerCustomLanguage();
449
- this.initMonaco(this.getOptions());
450
- }
451
- else {
452
- this.canLoad = true;
453
- }
454
- resolve();
455
- });
456
- });
457
- };
458
- if (!window.require) {
459
- const loaderScript = document.createElement('script');
460
- loaderScript.type = 'text/javascript';
461
- loaderScript.src = './assets/monaco/vs/loader.js';
462
- loaderScript.addEventListener('load', onGotAmdLoader);
687
+ if (!globalThis.require) {
688
+ this.installCspCompat();
689
+ const loaderScript = this.createLoaderScript();
690
+ loaderScript.addEventListener('load', () => this.onGotAmdLoader(resolve));
463
691
  document.body.appendChild(loaderScript);
464
692
  }
465
693
  });
466
694
  }
467
695
  }
696
+ /* istanbul ignore next */
697
+ onGotAmdLoader(resolve) {
698
+ globalThis.require.config(this.getLoaderConfig());
699
+ globalThis.require(['vs/editor/editor.main'], () => {
700
+ setTimeout(() => {
701
+ if (this.el.nativeElement.offsetWidth) {
702
+ this.registerCustomLanguage();
703
+ this.initMonaco(this.getOptions());
704
+ }
705
+ else {
706
+ this.canLoad = true;
707
+ }
708
+ resolve();
709
+ });
710
+ });
711
+ }
468
712
  ngDoCheck() {
469
713
  if (this.canLoad && this.el.nativeElement.offsetWidth) {
470
714
  this.registerCustomLanguage();
@@ -569,6 +813,39 @@ class PoCodeEditorComponent extends PoCodeEditorBaseComponent {
569
813
  }
570
814
  }
571
815
  }
816
+ installCspCompat() {
817
+ if (this.cspNonce) {
818
+ installMonacoCspCompat({
819
+ nonce: this.cspNonce,
820
+ monacoBaseUrl: new URL('./assets/monaco/vs/', document.baseURI).href
821
+ });
822
+ }
823
+ }
824
+ /**
825
+ * Cria o `<script>` do loader do Monaco, aplicando o nonce da CSP quando configurado.
826
+ */
827
+ createLoaderScript() {
828
+ const loaderScript = document.createElement('script');
829
+ loaderScript.type = 'text/javascript';
830
+ loaderScript.src = './assets/monaco/vs/loader.js';
831
+ if (this.cspNonce) {
832
+ loaderScript.nonce = this.cspNonce;
833
+ }
834
+ return loaderScript;
835
+ }
836
+ /**
837
+ * Retorna a configuração do loader AMD do Monaco. O loader aplica `cspNonce` nos scripts que carrega
838
+ * (ex.: editor.main.js).
839
+ */
840
+ getLoaderConfig() {
841
+ const requireConfig = {
842
+ paths: { 'vs': './assets/monaco/vs' }
843
+ };
844
+ if (this.cspNonce) {
845
+ requireConfig.cspNonce = this.cspNonce;
846
+ }
847
+ return requireConfig;
848
+ }
572
849
  static ɵfac = function PoCodeEditorComponent_Factory(__ngFactoryType__) { return new (__ngFactoryType__ || PoCodeEditorComponent)(i0.ɵɵdirectiveInject(i0.NgZone), i0.ɵɵdirectiveInject(i0.ElementRef), i0.ɵɵdirectiveInject(PoCodeEditorSuggestionService), i0.ɵɵdirectiveInject(PoCodeEditorRegister)); };
573
850
  static ɵcmp = /*@__PURE__*/ i0.ɵɵdefineComponent({ type: PoCodeEditorComponent, selectors: [["po-code-editor"]], viewQuery: function PoCodeEditorComponent_Query(rf, ctx) { if (rf & 1) {
574
851
  i0.ɵɵviewQuery(_c0, 7);
@@ -588,7 +865,7 @@ class PoCodeEditorComponent extends PoCodeEditorBaseComponent {
588
865
  type: ViewChild,
589
866
  args: ['editorContainer', { static: true }]
590
867
  }] }); })();
591
- (() => { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassDebugInfo(PoCodeEditorComponent, { className: "PoCodeEditorComponent", filePath: "lib/components/po-code-editor/po-code-editor.component.ts", lineNumber: 65 }); })();
868
+ (() => { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassDebugInfo(PoCodeEditorComponent, { className: "PoCodeEditorComponent", filePath: "lib/components/po-code-editor/po-code-editor.component.ts", lineNumber: 77 }); })();
592
869
 
593
870
  /**
594
871
  * @description
@@ -1 +1 @@
1
- {"version":3,"file":"po-ui-ng-code-editor.mjs","sources":["../../../projects/code-editor/src/lib/components/po-code-editor/po-code-editor-base.component.ts","../../../projects/code-editor/src/lib/components/po-code-editor/po-code-editor-suggestion.service.ts","../../../projects/code-editor/src/lib/components/po-code-editor/po-code-editor-register.service.ts","../../../projects/code-editor/src/lib/components/po-code-editor/po-code-editor.component.ts","../../../projects/code-editor/src/lib/components/po-code-editor/po-code-editor.component.html","../../../projects/code-editor/src/lib/components/po-code-editor/po-code-editor.module.ts","../../../projects/code-editor/src/po-ui-ng-code-editor.ts"],"sourcesContent":["import { Input, Directive } from '@angular/core';\nimport { ControlValueAccessor } from '@angular/forms';\n\nimport { PoCodeEditorRegisterableSuggestion } from './interfaces/po-code-editor-registerable-suggestion.interface';\n\nconst PO_CODE_EDITOR_THEMES = ['vs-dark', 'vs', 'hc-black'];\nconst PO_CODE_EDITOR_THEME_DEFAULT = 'vs';\n\n/**\n * @description\n *\n * O `po-code-editor` é um componente para edição de código fonte baseado no Monaco Editor da Microsoft.\n *\n * Sendo assim, algumas configurações presentes no Monaco podem ser utilizadas aqui, como a escolha da linguagem\n * (utilizando o highlight syntax específico), escolha do tema e opção de diff, além de ser muito similar ao Visual\n * Studio Code, com autocomplete e fechamento automático de brackets.\n *\n * Este componente pode ser usado em qualquer situação que necessite de adição de códigos, como por exemplo, criar\n * receitas utilizando Terraform para gerenciar topologias.\n * É importante ressaltar que este não é um componente para edição de textos comuns.\n *\n * O [(ngModel)] deve ser usado para manipular o conteúdo do po-code-editor, ou seja, tanto para incluir um conteúdo quanto\n * para recuperar o conteúdo do po-code-editor, utiliza-se uma variável passada por [(ngModel)].\n *\n * #### Adicionando o pacote @po-ui/ng-code-editor\n *\n * Para instalar o pacote `po-code-editor` em sua aplicação execute:\n *\n * ```shell\n * ng add @po-ui/ng-code-editor\n * ```\n *\n * O comando `ng add` do `Angular CLI`:\n * - inclui o `po-code-editor` no seu projeto;\n * - adiciona o módulo `PoCodeEditorModule`:;\n *\n * ```\n * // app.module.ts\n * ...\n * import { PoModule } from '@po-ui/ng-components';\n * import { PoCodeEditorModule } from '@po-ui/ng-code-editor';\n * ...\n * @NgModule({\n * imports: [\n * ...\n * PoModule,\n * PoCodeEditorModule\n * ],\n * ...\n * })\n * export class AppModule { }\n * ```\n *\n * - adiciona o tema PO UI e também o *asset* do Monaco no arquivo `angular.json`, conforme abaixo:\n *\n * <pre ngNonBindable>\n * ...\n * \"assets\": [\n * { \"glob\": \"&#42;&#42;/&#42;\", \"input\": \"node_modules/monaco-editor/min\", \"output\": \"/assets/monaco/\" }\n * ],\n * \"styles\": [\n * \"./node_modules/@po-ui/style/css/po-theme-default.min.css\"\n * ]\n * ...\n * </pre>\n */\n@Directive()\nexport abstract class PoCodeEditorBaseComponent implements ControlValueAccessor {\n editor: any;\n modifiedValue: string = '';\n value: any = '';\n\n private _height: number = 150;\n private _language = 'plainText';\n private _readonly: boolean = false;\n private _showDiff: boolean = false;\n private _suggestions: Array<PoCodeEditorRegisterableSuggestion>;\n private _theme = PO_CODE_EDITOR_THEME_DEFAULT;\n\n /**\n * @optional\n *\n * @description\n *\n * Linguagem na qual será apresentado o código fonte.\n * Para saber quais são as linguagens compatíveis, consulte a documentação oficial do\n * [**Monaco Editor**](https://microsoft.github.io/monaco-editor/).\n *\n * Também é possível adicionar uma nova linguagem personalizada utilizando o serviço:\n * [**po-code-editor-register**](https://po-ui.io/documentation/po-code-editor-register?view=doc).\n *\n * @default `plainText`\n */\n @Input('p-language') set language(language: string) {\n this._language = language && language.length ? language.trim() : 'plainText';\n\n if (this.editor && this._language) {\n this.setLanguage(this._language);\n }\n }\n\n get language(): string {\n return this._language;\n }\n\n /**\n * @optional\n *\n * @description\n *\n * Indica se o editor será aberto em modo de leitura.\n *\n * Neste caso, não é possível editar o código inserido.\n *\n * Obs: Esta propriedade não refletirá efeito se alterada após o carregamento do componente.\n *\n * @default `false`\n */\n @Input('p-readonly') set readonly(readonly: boolean) {\n this._readonly = <any>readonly === '' ? true : this.convertToBoolean(readonly);\n\n if (this.editor) {\n this.setReadOnly(readonly);\n }\n }\n\n get readonly(): boolean {\n return this._readonly;\n }\n\n /**\n * @optional\n *\n * @description\n *\n * Indica se o editor será aberto em modo de comparação.\n *\n * Caso esteja habilitada esta opção, então o [(ngModel)] deverá ser passado como um array, cuja primeira opção deve\n * conter uma string com o código original e na segunda posição uma string código modificado para efeito de\n * comparação. Neste caso, o usuário conseguirá editar apenas o código modificado e isso refletirá na segunda posição\n * do array consequentemente.\n *\n * Obs: Esta propriedade não refletirá efeito se alterada após o carregamento do componente.\n *\n * @default `false`\n */\n @Input('p-show-diff') set showDiff(showDiff: boolean) {\n this._showDiff = <any>showDiff === '' ? true : this.convertToBoolean(showDiff);\n }\n\n get showDiff(): boolean {\n return this._showDiff;\n }\n\n /**\n * @optional\n *\n * @description\n *\n * Lista de sugestões usadas pelo autocomplete dentro do editor.\n *\n * Para visualizar a lista de sugestões use o comando `CTRL + SPACE`.\n *\n * Caso o editor esteja usando uma linguagem que já tenha uma lista de sugestões predefinida, o valor passado será adicionado\n * a lista preexistente, aumentando as opções para o usuário.\n *\n * Caso tenha mais de um editor da mesma linguagem na aplicação, as sugestões serão adicionadas para que todos os editores da mesma linguagem\n * tenham as mesmas sugestões.\n *\n * ```\n * <po-code-editor\n * [p-suggestions]=\"[{ label: 'po', insertText: 'Portinari UI' }, { label: 'ng', insertText: 'Angular' }]\">\n * </po-code-editor>\n * ```\n *\n * Ao fornecer uma lista de sugestões é possível acelerar a escrita de scripts pelos usuários.\n */\n @Input('p-suggestions') set suggestions(values: Array<PoCodeEditorRegisterableSuggestion>) {\n this._suggestions = values;\n\n if (this.editor && this._suggestions) {\n this.setSuggestions(this._suggestions);\n }\n }\n\n get suggestions(): Array<PoCodeEditorRegisterableSuggestion> {\n return this._suggestions;\n }\n\n /**\n * @optional\n *\n * @description\n *\n * Define um tema para o editor.\n *\n * Temas válidos:\n * - `vs-dark`\n * - `vs`\n * - `hc-black`\n *\n * É importante salientar que o tema será aplicados a todos os componentes po-code-editor existentes na tela,\n * ou seja, todas as instâncias do componente receberão o último tema atribuído ou o tema da última instância\n * criada.\n *\n * @default `vs`\n */\n @Input('p-theme') set theme(theme: string) {\n this._theme = PO_CODE_EDITOR_THEMES.includes(theme) ? theme : PO_CODE_EDITOR_THEME_DEFAULT;\n\n if (this.editor) {\n this.setTheme(theme);\n }\n }\n\n get theme(): string {\n return this._theme;\n }\n\n /**\n * @optional\n *\n * @description\n *\n * Define a altura do componente em pixels do po-code-editor.\n * Esta propriedade não poderá ser alterada após o componente ter sido iniciado.\n * A altura mínima é 150 pixels.\n */\n @Input('p-height') set height(height: string) {\n this._height = parseFloat(height) >= 150 ? parseFloat(height) : 150;\n }\n\n get height(): string {\n return `${this._height}px`;\n }\n\n /* istanbul ignore next */\n onTouched = (value: any) => {};\n /* istanbul ignore next */\n onChangePropagate = (value: any) => {};\n\n getOptions() {\n return { language: this.language, theme: this.theme, readOnly: this.readonly };\n }\n\n registerOnChange(fn: any): void {\n this.onChangePropagate = fn;\n }\n\n registerOnTouched(fn: any): void {\n this.onTouched = fn;\n }\n\n protected convertToBoolean(val: any): boolean {\n if (typeof val === 'string') {\n val = val.toLowerCase().trim();\n return val === 'true' || val === 'on' || val === '';\n }\n\n if (typeof val === 'number') {\n return val === 1;\n }\n\n return !!val;\n }\n\n abstract writeValue(value: any);\n\n abstract setLanguage(value: any);\n\n abstract setTheme(value: any);\n\n abstract setReadOnly(value: any);\n\n abstract setSuggestions(value: any);\n}\n","import { Injectable } from '@angular/core';\nimport {\n PoCodeEditorSuggestionList,\n PoCodeEditorRegisterableSuggestion\n} from './interfaces/po-code-editor-registerable-suggestion.interface';\n\n@Injectable({\n providedIn: 'root'\n})\nexport class PoCodeEditorSuggestionService {\n private suggestions: PoCodeEditorSuggestionList = {};\n constructor() {}\n\n public getSuggestion(language: string, newSuggestion: Array<PoCodeEditorRegisterableSuggestion>) {\n if (this.suggestions[language]) {\n const deduplicateSuggestions = this.deduplicateSuggestions(this.suggestions[language], newSuggestion);\n this.suggestions[language] = [...this.suggestions[language], ...deduplicateSuggestions];\n return deduplicateSuggestions;\n } else {\n return (this.suggestions[language] = [...newSuggestion]);\n }\n }\n\n private deduplicateSuggestions(\n originalSuggestions: Array<PoCodeEditorRegisterableSuggestion>,\n newSuggestions: Array<PoCodeEditorRegisterableSuggestion>\n ) {\n return newSuggestions.filter(\n newItem => !originalSuggestions.find(originalItem => originalItem['label'] === newItem['label'])\n );\n }\n}\n","import { Injectable } from '@angular/core';\n\nimport { PoCodeEditorRegisterable } from './interfaces/po-code-editor-registerable.interface';\nimport { PoCodeEditorRegisterableOptions } from './interfaces/po-code-editor-registerable-options.interface';\nimport { PoCodeEditorRegisterableSuggestionType } from './interfaces/po-code-editor-registerable-suggestion.interface';\n\n/**\n * @description\n *\n * Wrapper para registro de sintaxes customizadas para o po-code-editor.\n *\n * Para utilização do serviço de idiomas **PoCodeEditorRegister**,\n * deve-se importar o módulo PoCodeEditorModule mesmo já tendo importado\n * o módulo PoModule.\n * Na importação opcionalmente pode ser invocado o método **forRegister** informando um objeto para configuração.\n *\n * Exemplo de configuração:\n * ```\n * import { PoCodeEditorModule, PoCodeEditorRegisterable } from '@po-ui/ng-code-editor';\n *\n * declare const monaco: any; // Importante para usar configurações com tipos definidos pelo Monaco\n *\n * // A função `provideCompletionItems` precisa ser exportada para ser compatível com AOT.\n * export function provideCompletionItems() {\n * const suggestions = [{\n * label: 'terraform',\n * insertText: '#terraform language'\n * }, {\n * label: 'server',\n * insertText: 'server ${1:ip}'\n * }];\n *\n * return { suggestions: suggestions };\n * }\n *\n * const customEditor: PoCodeEditorRegisterable = {\n * language: 'terraform',\n * options: {\n * keywords: ['resource', 'provider', 'variable', 'output', 'module', 'true', 'false'],\n * operators: ['{', '}', '(', ')', '[', ']', '?', ':'],\n * symbols: /[=><!~?:&|+\\-*\\/\\^%]+/,\n * escapes: /\\\\(?:[abfnrtv\\\\\"']|x[0-9A-Fa-f]{1,4}|u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8})/,\n * tokenizer: {\n * ...\n * }\n * },\n * suggestions: { provideCompletionItems: provideCompletionItems }\n * };\n *\n * @NgModule({\n * declarations: [],\n * imports: [\n * PoModule,\n * PoCodeEditorModule.forRegister(customEditor)\n * ],\n * bootstrap: [AppComponent]\n * })\n * ```\n *\n * > As configurações para o registro de uma nova sintaxe no Monaco code editor podem ser encontradas em\n * > [**Monaco Editor**](https://microsoft.github.io/monaco-editor/playground.html#extending-language-services-custom-languages).\n */\n@Injectable({\n providedIn: 'root'\n})\nexport class PoCodeEditorRegister implements PoCodeEditorRegisterable {\n /** Sintaxe a ser registrada. */\n language: string;\n\n /** Opções da sintaxe para registro no po-code-editor. */\n options: PoCodeEditorRegisterableOptions;\n\n /** Lista de sugestões para a função de autocomplete (CTRL + SPACE). */\n suggestions?: PoCodeEditorRegisterableSuggestionType;\n}\n","import { AfterViewInit, Component, DoCheck, ElementRef, forwardRef, NgZone, ViewChild, Provider } from '@angular/core';\nimport { NG_VALUE_ACCESSOR } from '@angular/forms';\n\nimport { PoCodeEditorBaseComponent } from './po-code-editor-base.component';\nimport { PoCodeEditorRegister } from './po-code-editor-register.service';\nimport { PoCodeEditorRegisterableSuggestion } from './interfaces/po-code-editor-registerable-suggestion.interface';\nimport { PoCodeEditorSuggestionService } from './po-code-editor-suggestion.service';\n\n// variáveis relacionadas ao Monaco\nlet loadedMonaco: boolean = false;\nlet loadPromise: Promise<void>;\n\ndeclare const monaco: any;\n// eslint-disable-next-line\ndeclare const require: any;\n\n/* istanbul ignore next */\nconst providers: Array<Provider> = [\n {\n provide: NG_VALUE_ACCESSOR,\n // eslint-disable-next-line\n useExisting: forwardRef(() => PoCodeEditorComponent),\n multi: true\n }\n];\n\n/**\n * @docsExtends PoCodeEditorBaseComponent\n *\n * @example\n *\n * <example name=\"po-code-editor-basic\" title=\"PO Code Editor Basic\">\n * <file name=\"sample-po-code-editor-basic/sample-po-code-editor-basic.component.html\"> </file>\n * <file name=\"sample-po-code-editor-basic/sample-po-code-editor-basic.component.ts\"> </file>\n * </example>\n *\n * <example name=\"po-code-editor-labs\" title=\"PO Code Editor Labs\">\n * <file name=\"sample-po-code-editor-labs/sample-po-code-editor-labs.component.html\"> </file>\n * <file name=\"sample-po-code-editor-labs/sample-po-code-editor-labs.component.ts\"> </file>\n * </example>\n *\n * <example name=\"po-code-editor-diff\" title=\"PO Code Editor - Diff\">\n * <file name=\"sample-po-code-editor-diff/sample-po-code-editor-diff.component.html\"> </file>\n * <file name=\"sample-po-code-editor-diff/sample-po-code-editor-diff.component.ts\"> </file>\n * </example>\n *\n * <example name=\"po-code-editor-terraform\" title=\"PO Code Editor - Terraform\">\n * <file name=\"sample-po-code-editor-terraform/sample-po-code-editor-terraform.component.html\"> </file>\n * <file name=\"sample-po-code-editor-terraform/sample-po-code-editor-terraform.component.ts\"> </file>\n * <file name=\"sample-po-code-editor-terraform/sample-po-code-editor-terraform.constant.ts\"> </file>\n * <file name=\"sample-po-code-editor-terraform/sample-po-code-editor-terraform.module.ts\"> </file>\n * </example>\n *\n * <example name=\"po-code-editor-suggestion\" title=\"PO Code Editor Suggestion\">\n * <file name=\"sample-po-code-editor-suggestion/sample-po-code-editor-suggestion.component.html\"> </file>\n * <file name=\"sample-po-code-editor-suggestion/sample-po-code-editor-suggestion.component.ts\"> </file>\n * </example>\n */\n@Component({\n selector: 'po-code-editor',\n templateUrl: './po-code-editor.component.html',\n providers,\n standalone: false\n})\nexport class PoCodeEditorComponent extends PoCodeEditorBaseComponent implements AfterViewInit, DoCheck {\n @ViewChild('editorContainer', { static: true }) editorContainer: ElementRef;\n\n canLoad = false;\n\n constructor(\n private zone: NgZone,\n private el: ElementRef,\n private poCodeEditorSuggestionService: PoCodeEditorSuggestionService,\n private codeEditorRegister?: PoCodeEditorRegister\n ) {\n super();\n }\n\n /* istanbul ignore next */\n ngAfterViewInit(): void {\n if (loadedMonaco) {\n /* istanbul ignore next */\n loadPromise.then(() => {\n setTimeout(() => {\n if (this.el.nativeElement.offsetWidth) {\n this.registerCustomLanguage();\n this.initMonaco(this.getOptions());\n } else {\n this.canLoad = true;\n }\n });\n });\n } else {\n loadedMonaco = true;\n loadPromise = new Promise<void>((resolve: any) => {\n /* istanbul ignore next */\n const onGotAmdLoader: any = () => {\n (<any>window).require.config({ paths: { 'vs': './assets/monaco/vs' } });\n (<any>window).require(['vs/editor/editor.main'], () => {\n setTimeout(() => {\n if (this.el.nativeElement.offsetWidth) {\n this.registerCustomLanguage();\n this.initMonaco(this.getOptions());\n } else {\n this.canLoad = true;\n }\n resolve();\n });\n });\n };\n\n if (!(<any>window).require) {\n const loaderScript: HTMLScriptElement = document.createElement('script');\n loaderScript.type = 'text/javascript';\n loaderScript.src = './assets/monaco/vs/loader.js';\n loaderScript.addEventListener('load', onGotAmdLoader);\n document.body.appendChild(loaderScript);\n }\n });\n }\n }\n\n ngDoCheck() {\n if (this.canLoad && this.el.nativeElement.offsetWidth) {\n this.registerCustomLanguage();\n this.initMonaco(this.getOptions());\n this.canLoad = false;\n }\n }\n\n /* istanbul ignore next */\n monacoCreateModel(value: string) {\n return monaco.editor.createModel(value);\n }\n\n setValueInEditor() {\n if (this.showDiff) {\n setTimeout(() => {\n if (this.editor) {\n this.editor.setModel({\n original: this.monacoCreateModel(this.value),\n modified: this.monacoCreateModel(this.modifiedValue)\n });\n }\n });\n } else {\n setTimeout(() => {\n if (this.editor) {\n this.editor.setValue(this.value);\n }\n });\n }\n }\n\n setLanguage(language: string) {\n if (this.showDiff) {\n this.setMonacoLanguage(this.editor.getModel().original, language);\n this.setMonacoLanguage(this.editor.getModel().modified, language);\n } else {\n this.setMonacoLanguage(this.editor.getModel(), language);\n }\n }\n\n /* istanbul ignore next */\n setTheme(theme: string) {\n monaco.editor.setTheme(theme);\n }\n\n setReadOnly(readOnly: boolean) {\n this.editor.updateOptions({ readOnly: readOnly });\n }\n\n /* istanbul ignore next */\n setSuggestions(newSuggestions: Array<PoCodeEditorRegisterableSuggestion>, language = this.language) {\n if (!newSuggestions) {\n return;\n }\n\n const suggestions = this.poCodeEditorSuggestionService.getSuggestion(language, newSuggestions);\n\n monaco.languages.registerCompletionItemProvider(language, {\n provideCompletionItems: () => ({ suggestions })\n });\n }\n\n writeValue(value) {\n this.value = value && value instanceof Array ? value[0] : value;\n this.modifiedValue = value && value instanceof Array && value.length > 0 ? value[1] : '';\n this.setValueInEditor();\n }\n\n /* istanbul ignore next */\n private initMonaco(options: any): void {\n if (this.showDiff) {\n this.editor = monaco.editor.createDiffEditor(this.editorContainer.nativeElement, options);\n\n this.editor.setModel({\n original: monaco.editor.createModel(this.value),\n modified: monaco.editor.createModel(this.modifiedValue)\n });\n\n this.editor.onDidUpdateDiff((e: any) => {\n const original = this.editor.getModel().original.getValue();\n const modified = this.editor.getModel().modified.getValue();\n this.onChangePropagate([original, modified]);\n });\n } else {\n this.editor = monaco.editor.create(this.editorContainer.nativeElement, options);\n this.editor.setValue(this.value);\n this.editor.onDidChangeModelContent((e: any) => {\n const value = this.editor.getValue();\n this.onChangePropagate(value);\n this.zone.run(() => (this.value = value));\n });\n }\n setTimeout(() => {\n this.setLanguage(this.language);\n this.setSuggestions(this.suggestions);\n }, 500);\n }\n\n /* istanbul ignore next */\n private setMonacoLanguage(model, language) {\n monaco.editor.setModelLanguage(model, language);\n }\n\n private registerCustomLanguage() {\n if (this.codeEditorRegister.language) {\n monaco.languages.register({ id: this.codeEditorRegister.language });\n\n if (this.codeEditorRegister.options) {\n monaco.languages.setMonarchTokensProvider(this.codeEditorRegister.language, this.codeEditorRegister.options);\n }\n\n if (this.codeEditorRegister.suggestions) {\n this.setSuggestions(\n this.codeEditorRegister.suggestions.provideCompletionItems().suggestions,\n this.codeEditorRegister.language\n );\n }\n }\n }\n}\n","<div #editorContainer [style.height]=\"height\"></div>\n","import { NgModule, ModuleWithProviders } from '@angular/core';\nimport { CommonModule } from '@angular/common';\n\nimport { PoCodeEditorComponent } from './po-code-editor.component';\nimport { PoCodeEditorRegister } from './po-code-editor-register.service';\nimport { PoCodeEditorRegisterable } from './interfaces/po-code-editor-registerable.interface';\n\n/**\n * @description\n *\n * Módulo do componente po-code-editor.\n */\n@NgModule({\n imports: [CommonModule],\n declarations: [PoCodeEditorComponent],\n exports: [PoCodeEditorComponent],\n providers: [PoCodeEditorRegister]\n})\nexport class PoCodeEditorModule {\n static forRegister(props: PoCodeEditorRegisterable): ModuleWithProviders<PoCodeEditorModule> {\n return {\n ngModule: PoCodeEditorModule,\n providers: [\n {\n provide: PoCodeEditorRegister,\n useValue: props\n }\n ]\n };\n }\n}\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './public-api';\n"],"names":["i1.PoCodeEditorSuggestionService","i2.PoCodeEditorRegister"],"mappings":";;;;;AAKA,MAAM,qBAAqB,GAAG,CAAC,SAAS,EAAE,IAAI,EAAE,UAAU,CAAC;AAC3D,MAAM,4BAA4B,GAAG,IAAI;AAEzC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyDG;MAEmB,yBAAyB,CAAA;AAC7C,IAAA,MAAM;IACN,aAAa,GAAW,EAAE;IAC1B,KAAK,GAAQ,EAAE;IAEP,OAAO,GAAW,GAAG;IACrB,SAAS,GAAG,WAAW;IACvB,SAAS,GAAY,KAAK;IAC1B,SAAS,GAAY,KAAK;AAC1B,IAAA,YAA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CAAA,CAAA,CAAA,GAAA;;ACfjC;;AAEG;;;;"}
1
+ {"version":3,"file":"po-ui-ng-code-editor.mjs","sources":["../../../projects/code-editor/src/lib/components/po-code-editor/po-code-editor-csp-compat.ts","../../../projects/code-editor/src/lib/components/po-code-editor/po-code-editor-base.component.ts","../../../projects/code-editor/src/lib/components/po-code-editor/po-code-editor-suggestion.service.ts","../../../projects/code-editor/src/lib/components/po-code-editor/po-code-editor-register.service.ts","../../../projects/code-editor/src/lib/components/po-code-editor/po-code-editor.component.ts","../../../projects/code-editor/src/lib/components/po-code-editor/po-code-editor.component.html","../../../projects/code-editor/src/lib/components/po-code-editor/po-code-editor.module.ts","../../../projects/code-editor/src/po-ui-ng-code-editor.ts"],"sourcesContent":["/**\n * @docsPrivate\n *\n * Camada de compatibilidade entre o Monaco Editor (`0.44.0`) e Content-Security-Policy (CSP) baseada em *nonce*.\n *\n * O Monaco não oferece opção de *nonce* para os estilos que cria em tempo de execução. Sem esta camada, uma política\n * sem `'unsafe-inline'` bloqueia:\n *\n * 1. os elementos `<style>` criados pelo Monaco (`document.createElement('style')`, inclusive no *shadow DOM* do menu\n * de contexto). **Correção:** o *nonce* é aplicado somente nos `<style>` criados por código do Monaco;\n * 2. os atributos `style` do HTML que o Monaco monta como texto (linhas, números de linha, seleção, decorações etc.).\n * O *nonce* não se aplica a atributos. **Correção:** o HTML passa pelo *hook* público\n * `MonacoEnvironment.createTrustedTypesPolicy`; o atributo `style` das tags é renomeado para um atributo de marcação e,\n * logo após a inserção no DOM (na mesma tarefa), o valor é aplicado via CSSOM (`element.style.cssText`), que a CSP não\n * bloqueia;\n * 3. o `setAttribute('style', ...)` usado pelo Monaco (indicadores do modo diff). **Correção:** quando a chamada vem\n * do Monaco, o valor é aplicado via CSSOM.\n *\n * Escopo:\n * - A camada só é instalada quando a aplicação informa o `CSP_NONCE`, uma vez por página, antes do carregamento do\n * Monaco.\n * - Apenas o HTML produzido pelas políticas de Trusted Types do Monaco é convertido. O Monaco escapa `<`, `>` e `&` no\n * conteúdo do usuário, então o conteúdo não consegue criar tags nem atributos. As demais atribuições de `innerHTML`\n * da página não são alteradas.\n * - Chamadas de `createElement` e `setAttribute` só são alteradas quando o código do Monaco está na pilha de chamadas\n * (identificado pela URL da pasta `vs` do Monaco). Se essa identificação falhar, o comportamento é o anterior.\n */\n\n/** Atributo de marcação que substitui o `style` no HTML gerado pelo Monaco até a aplicação via CSSOM. */\nexport const PO_CSP_STYLE_MARKER = 'data-po-csp-style';\n\nconst INSTALLED_KEY = '__poCodeEditorCspCompat';\n\n/**\n * Tags do HTML gerado pelo Monaco. Como o Monaco escapa `<` e `>` no conteúdo, cada trecho `<...>` é uma tag.\n */\nconst TAG_REGEX = /<[a-zA-Z][^<>]*>/g;\n\n/** Atributo `style` dentro de uma tag (precedido de espaço, para não alcançar, por exemplo, `data-style`). */\nconst STYLE_ATTRIBUTE_REGEX = /(\\s)style=([\"'])/g;\n\nexport interface PoMonacoCspCompatOptions {\n /** Nonce da política (o mesmo valor do token `CSP_NONCE`). */\n nonce: string;\n\n /** URL absoluta da pasta `vs` do Monaco, usada para identificar chamadas originadas no código do Monaco. */\n monacoBaseUrl: string;\n}\n\n/** HTML gerado pelo Monaco quando o navegador não oferece Trusted Types. É convertido em texto pelo navegador. */\nclass PoCspMarkedHtml {\n constructor(private readonly html: string) {}\n\n toString(): string {\n return this.html;\n }\n}\n\n/**\n * Renomeia o atributo `style` das tags do HTML para o atributo de marcação. O conteúdo de texto não é alterado.\n */\nexport function rewriteStyleAttributes(html: string): string {\n if (typeof html !== 'string' || !html.includes('style=')) {\n return html;\n }\n\n return html.replaceAll(TAG_REGEX, tag => tag.replaceAll(STYLE_ATTRIBUTE_REGEX, `$1${PO_CSP_STYLE_MARKER}=$2`));\n}\n\n/**\n * Aplica via CSSOM os estilos marcados no elemento e nos seus descendentes e remove o atributo de marcação.\n */\nexport function applyMarkedStyles(root: Element | null | undefined): void {\n if (!root) {\n return;\n }\n\n if (root.hasAttribute(PO_CSP_STYLE_MARKER)) {\n applyMarkedStyle(root);\n }\n\n root.querySelectorAll(`[${PO_CSP_STYLE_MARKER}]`).forEach(applyMarkedStyle);\n}\n\n/**\n * Instala a camada de compatibilidade. A instalação é única por página: chamadas seguintes reaproveitam a primeira.\n *\n * @returns Função que desfaz a instalação (usada nos testes).\n */\nexport function installMonacoCspCompat(options: PoMonacoCspCompatOptions): () => void {\n const win = globalThis as any;\n\n if (win[INSTALLED_KEY]) {\n return win[INSTALLED_KEY].dispose;\n }\n\n const { nonce, monacoBaseUrl } = options;\n const producedHtml = new WeakSet<object>();\n\n const isProducedHtml = (value: unknown): boolean =>\n value !== null && typeof value === 'object' && producedHtml.has(value);\n\n const isCalledFromMonaco = (): boolean => {\n const stack = new Error('po-code-editor-csp-compat: call origin').stack;\n return !!stack && stack.includes(monacoBaseUrl);\n };\n\n const markHtml = (html: any): any => {\n if (typeof html === 'string') {\n const marked = new PoCspMarkedHtml(html);\n producedHtml.add(marked);\n return marked;\n }\n\n if (html !== null && typeof html === 'object') {\n producedHtml.add(html);\n }\n\n return html;\n };\n\n // 1) <style> criados pelo Monaco recebem o nonce.\n const originalCreateElement = Document.prototype.createElement;\n Document.prototype.createElement = function (this: Document, tagName: string, elementOptions?: any) {\n const element = originalCreateElement.call(this, tagName, elementOptions);\n\n if (isStyleTag(tagName) && !element.nonce && isCalledFromMonaco()) {\n element.setAttribute('nonce', nonce);\n }\n\n return element;\n } as typeof Document.prototype.createElement;\n\n // 2) setAttribute('style', ...) do Monaco passa a ser aplicado via CSSOM.\n const originalSetAttribute = Element.prototype.setAttribute;\n Element.prototype.setAttribute = function (this: Element, name: string, value: string): void {\n if (name === 'style' && (this as HTMLElement).style && isCalledFromMonaco()) {\n (this as HTMLElement).style.cssText = String(value);\n return;\n }\n\n return originalSetAttribute.call(this, name, value);\n };\n\n // 3) HTML gerado pelo Monaco: o atributo style é marcado na criação do HTML...\n const environment = (win.MonacoEnvironment = win.MonacoEnvironment || {});\n const previousPolicyFactory = environment.createTrustedTypesPolicy;\n\n const createPolicy = (name: string, policyOptions?: any): any =>\n previousPolicyFactory\n ? previousPolicyFactory.call(environment, name, policyOptions)\n : win.trustedTypes?.createPolicy?.(name, policyOptions);\n\n environment.createTrustedTypesPolicy = (name: string, policyOptions?: any): any => {\n if (!policyOptions || typeof policyOptions.createHTML !== 'function') {\n return createPolicy(name, policyOptions);\n }\n\n const wrappedOptions = {\n ...policyOptions,\n createHTML: (input: string, ...args: Array<any>) =>\n rewriteStyleAttributes(policyOptions.createHTML(input, ...args))\n };\n\n const policy = createPolicy(name, wrappedOptions);\n\n if (!policy) {\n // Navegador sem Trusted Types: o HTML marcado é convertido em texto pelo setter de innerHTML.\n return {\n name,\n createHTML: (input: string, ...args: Array<any>) => markHtml(wrappedOptions.createHTML(input, ...args))\n };\n }\n\n return {\n name: policy.name ?? name,\n createHTML: (input: string, ...args: Array<any>) => markHtml(policy.createHTML(input, ...args)),\n createScript: policy.createScript?.bind(policy),\n createScriptURL: policy.createScriptURL?.bind(policy)\n };\n };\n\n // ... e aplicado via CSSOM logo após a inserção (mesma tarefa, antes das medições do Monaco).\n const innerHTMLDescriptor = Object.getOwnPropertyDescriptor(Element.prototype, 'innerHTML');\n\n if (innerHTMLDescriptor?.set) {\n Object.defineProperty(Element.prototype, 'innerHTML', {\n ...innerHTMLDescriptor,\n set(this: Element, value: unknown) {\n innerHTMLDescriptor.set.call(this, value);\n\n if (isProducedHtml(value)) {\n applyMarkedStyles(this);\n }\n }\n });\n }\n\n const originalInsertAdjacentHTML = Element.prototype.insertAdjacentHTML;\n Element.prototype.insertAdjacentHTML = function (this: Element, position: InsertPosition, text: string): void {\n originalInsertAdjacentHTML.call(this, position, text);\n\n if (isProducedHtml(text)) {\n const insertsAsSibling = /^(beforebegin|afterend)$/i.test(String(position));\n applyMarkedStyles(insertsAsSibling ? this.parentElement : this);\n }\n };\n\n const dispose = (): void => {\n Document.prototype.createElement = originalCreateElement;\n Element.prototype.setAttribute = originalSetAttribute;\n Element.prototype.insertAdjacentHTML = originalInsertAdjacentHTML;\n\n if (innerHTMLDescriptor) {\n Object.defineProperty(Element.prototype, 'innerHTML', innerHTMLDescriptor);\n }\n\n if (previousPolicyFactory) {\n environment.createTrustedTypesPolicy = previousPolicyFactory;\n } else {\n delete environment.createTrustedTypesPolicy;\n }\n\n delete win[INSTALLED_KEY];\n };\n\n win[INSTALLED_KEY] = { dispose };\n\n return dispose;\n}\n\n/** Desfaz a instalação, se houver (usada nos testes). */\nexport function disposeMonacoCspCompat(): void {\n (globalThis as any)[INSTALLED_KEY]?.dispose();\n}\n\nfunction isStyleTag(tagName: string): boolean {\n return typeof tagName === 'string' && tagName.length === 5 && tagName.toLowerCase() === 'style';\n}\n\nfunction applyMarkedStyle(element: Element): void {\n const css = element.getAttribute(PO_CSP_STYLE_MARKER) ?? '';\n element.removeAttribute(PO_CSP_STYLE_MARKER);\n\n const style = (element as HTMLElement).style;\n\n if (style) {\n style.cssText = css;\n }\n}\n","import { Input, Directive } from '@angular/core';\nimport { ControlValueAccessor } from '@angular/forms';\n\nimport { PoCodeEditorRegisterableSuggestion } from './interfaces/po-code-editor-registerable-suggestion.interface';\n\nconst PO_CODE_EDITOR_THEMES = ['vs-dark', 'vs', 'hc-black'];\nconst PO_CODE_EDITOR_THEME_DEFAULT = 'vs';\n\n/**\n * @description\n *\n * O `po-code-editor` é um componente para edição de código fonte baseado no Monaco Editor da Microsoft.\n *\n * Sendo assim, algumas configurações presentes no Monaco podem ser utilizadas aqui, como a escolha da linguagem\n * (utilizando o highlight syntax específico), escolha do tema e opção de diff, além de ser muito similar ao Visual\n * Studio Code, com autocomplete e fechamento automático de brackets.\n *\n * Este componente pode ser usado em qualquer situação que necessite de adição de códigos, como por exemplo, criar\n * receitas utilizando Terraform para gerenciar topologias.\n * É importante ressaltar que este não é um componente para edição de textos comuns.\n *\n * O [(ngModel)] deve ser usado para manipular o conteúdo do po-code-editor, ou seja, tanto para incluir um conteúdo quanto\n * para recuperar o conteúdo do po-code-editor, utiliza-se uma variável passada por [(ngModel)].\n *\n * #### Adicionando o pacote @po-ui/ng-code-editor\n *\n * Para instalar o pacote `po-code-editor` em sua aplicação execute:\n *\n * ```shell\n * ng add @po-ui/ng-code-editor\n * ```\n *\n * O comando `ng add` do `Angular CLI`:\n * - inclui o `po-code-editor` no seu projeto;\n * - adiciona o módulo `PoCodeEditorModule`:;\n *\n * ```\n * // app.module.ts\n * ...\n * import { PoModule } from '@po-ui/ng-components';\n * import { PoCodeEditorModule } from '@po-ui/ng-code-editor';\n * ...\n * @NgModule({\n * imports: [\n * ...\n * PoModule,\n * PoCodeEditorModule\n * ],\n * ...\n * })\n * export class AppModule { }\n * ```\n *\n * - adiciona o tema PO UI e também o *asset* do Monaco no arquivo `angular.json`, conforme abaixo:\n *\n * <pre ngNonBindable>\n * ...\n * \"assets\": [\n * { \"glob\": \"&#42;&#42;/&#42;\", \"input\": \"node_modules/monaco-editor/min\", \"output\": \"/assets/monaco/\" }\n * ],\n * \"styles\": [\n * \"./node_modules/@po-ui/style/css/po-theme-default.min.css\"\n * ]\n * ...\n * </pre>\n *\n * #### Content Security Policy (CSP)\n *\n * O `po-code-editor` é compatível com políticas de segurança restritivas (CSP) baseadas em *nonce*, sem a necessidade\n * de `'unsafe-inline'` em `script-src`, `style-src`, `style-src-elem` ou `style-src-attr`.\n *\n * O *nonce* é obtido do token `CSP_NONCE` do Angular, ou do atributo `ngCspNonce` em um elemento do `body`\n * (normalmente o `<app-root>`). Não existe configuração específica do PO UI para isso e não é necessário chamar\n * nenhum método ou informar nenhuma propriedade no componente.\n *\n * ```\n * <!-- index.html -->\n * <app-root ngCspNonce=\"NONCE_DA_REQUISICAO\"></app-root>\n * ```\n *\n * ou\n *\n * ```\n * import { CSP_NONCE } from '@angular/core';\n *\n * providers: [{ provide: CSP_NONCE, useValue: nonceDaRequisicao }]\n * ```\n *\n * Quando o *nonce* é informado, o `po-code-editor`:\n *\n * - aplica o *nonce* no `<script>` do `loader.js` do Monaco e o repassa à configuração do *loader* (`cspNonce`), que\n * o aplica nos scripts que ele mesmo carrega;\n * - aplica o *nonce* nos elementos `<style>` criados pelo Monaco, inclusive no *shadow DOM* do menu de contexto;\n * - aplica, via CSSOM (`element.style`), os estilos que o Monaco define no atributo `style` dos elementos (posição das\n * linhas, números de linha, seleção, decorações e indicadores do modo de comparação), pois o *nonce* não se aplica a\n * atributos.\n *\n * Esses ajustes valem apenas para os elementos criados pelo Monaco e não alteram o restante da aplicação.\n *\n * **Pontos de atenção**\n *\n * - O valor informado deve ser o mesmo *nonce* enviado na política (`'nonce-...'`) da requisição atual.\n * - O Monaco é carregado apenas uma vez por carregamento da página, quando o primeiro `po-code-editor` é exibido.\n * Por isso, o *nonce* deve estar disponível antes disso.\n * - O Monaco deve ser servido a partir de `assets/monaco/vs`, como configurado pelo `ng add @po-ui/ng-code-editor`.\n * - Quando o *nonce* não é informado, o componente se comporta como antes: nenhum ajuste é aplicado.\n * - A política também precisa permitir os demais recursos do Monaco (por exemplo, `worker-src` e `font-src`). Valide\n * a política utilizada em um ambiente de teste antes de aplicá-la em produção.\n *\n * > **Atenção:** não utilize `'unsafe-inline'` em `style-src`, `style-src-elem` ou `style-src-attr` para contornar\n * > bloqueios do editor. Quando a diretiva possui um *nonce*, o navegador ignora o `'unsafe-inline'`; e, caso o *nonce*\n * > seja removido para que ele valha, qualquer estilo injetado passa a ser aceito, o que enfraquece a política.\n */\n@Directive()\nexport abstract class PoCodeEditorBaseComponent implements ControlValueAccessor {\n editor: any;\n modifiedValue: string = '';\n value: any = '';\n\n private _height: number = 150;\n private _language = 'plainText';\n private _readonly: boolean = false;\n private _showDiff: boolean = false;\n private _suggestions: Array<PoCodeEditorRegisterableSuggestion>;\n private _theme = PO_CODE_EDITOR_THEME_DEFAULT;\n\n /**\n * @optional\n *\n * @description\n *\n * Linguagem na qual será apresentado o código fonte.\n * Para saber quais são as linguagens compatíveis, consulte a documentação oficial do\n * [**Monaco Editor**](https://microsoft.github.io/monaco-editor/).\n *\n * Também é possível adicionar uma nova linguagem personalizada utilizando o serviço:\n * [**po-code-editor-register**](https://po-ui.io/documentation/po-code-editor-register?view=doc).\n *\n * @default `plainText`\n */\n @Input('p-language') set language(language: string) {\n this._language = language && language.length ? language.trim() : 'plainText';\n\n if (this.editor && this._language) {\n this.setLanguage(this._language);\n }\n }\n\n get language(): string {\n return this._language;\n }\n\n /**\n * @optional\n *\n * @description\n *\n * Indica se o editor será aberto em modo de leitura.\n *\n * Neste caso, não é possível editar o código inserido.\n *\n * Obs: Esta propriedade não refletirá efeito se alterada após o carregamento do componente.\n *\n * @default `false`\n */\n @Input('p-readonly') set readonly(readonly: boolean) {\n this._readonly = <any>readonly === '' ? true : this.convertToBoolean(readonly);\n\n if (this.editor) {\n this.setReadOnly(readonly);\n }\n }\n\n get readonly(): boolean {\n return this._readonly;\n }\n\n /**\n * @optional\n *\n * @description\n *\n * Indica se o editor será aberto em modo de comparação.\n *\n * Caso esteja habilitada esta opção, então o [(ngModel)] deverá ser passado como um array, cuja primeira opção deve\n * conter uma string com o código original e na segunda posição uma string código modificado para efeito de\n * comparação. Neste caso, o usuário conseguirá editar apenas o código modificado e isso refletirá na segunda posição\n * do array consequentemente.\n *\n * Obs: Esta propriedade não refletirá efeito se alterada após o carregamento do componente.\n *\n * @default `false`\n */\n @Input('p-show-diff') set showDiff(showDiff: boolean) {\n this._showDiff = <any>showDiff === '' ? true : this.convertToBoolean(showDiff);\n }\n\n get showDiff(): boolean {\n return this._showDiff;\n }\n\n /**\n * @optional\n *\n * @description\n *\n * Lista de sugestões usadas pelo autocomplete dentro do editor.\n *\n * Para visualizar a lista de sugestões use o comando `CTRL + SPACE`.\n *\n * Caso o editor esteja usando uma linguagem que já tenha uma lista de sugestões predefinida, o valor passado será adicionado\n * a lista preexistente, aumentando as opções para o usuário.\n *\n * Caso tenha mais de um editor da mesma linguagem na aplicação, as sugestões serão adicionadas para que todos os editores da mesma linguagem\n * tenham as mesmas sugestões.\n *\n * ```\n * <po-code-editor\n * [p-suggestions]=\"[{ label: 'po', insertText: 'Portinari UI' }, { label: 'ng', insertText: 'Angular' }]\">\n * </po-code-editor>\n * ```\n *\n * Ao fornecer uma lista de sugestões é possível acelerar a escrita de scripts pelos usuários.\n */\n @Input('p-suggestions') set suggestions(values: Array<PoCodeEditorRegisterableSuggestion>) {\n this._suggestions = values;\n\n if (this.editor && this._suggestions) {\n this.setSuggestions(this._suggestions);\n }\n }\n\n get suggestions(): Array<PoCodeEditorRegisterableSuggestion> {\n return this._suggestions;\n }\n\n /**\n * @optional\n *\n * @description\n *\n * Define um tema para o editor.\n *\n * Temas válidos:\n * - `vs-dark`\n * - `vs`\n * - `hc-black`\n *\n * É importante salientar que o tema será aplicados a todos os componentes po-code-editor existentes na tela,\n * ou seja, todas as instâncias do componente receberão o último tema atribuído ou o tema da última instância\n * criada.\n *\n * @default `vs`\n */\n @Input('p-theme') set theme(theme: string) {\n this._theme = PO_CODE_EDITOR_THEMES.includes(theme) ? theme : PO_CODE_EDITOR_THEME_DEFAULT;\n\n if (this.editor) {\n this.setTheme(theme);\n }\n }\n\n get theme(): string {\n return this._theme;\n }\n\n /**\n * @optional\n *\n * @description\n *\n * Define a altura do componente em pixels do po-code-editor.\n * Esta propriedade não poderá ser alterada após o componente ter sido iniciado.\n * A altura mínima é 150 pixels.\n */\n @Input('p-height') set height(height: string) {\n this._height = parseFloat(height) >= 150 ? parseFloat(height) : 150;\n }\n\n get height(): string {\n return `${this._height}px`;\n }\n\n /* istanbul ignore next */\n onTouched = (value: any) => {};\n /* istanbul ignore next */\n onChangePropagate = (value: any) => {};\n\n getOptions() {\n return { language: this.language, theme: this.theme, readOnly: this.readonly };\n }\n\n registerOnChange(fn: any): void {\n this.onChangePropagate = fn;\n }\n\n registerOnTouched(fn: any): void {\n this.onTouched = fn;\n }\n\n protected convertToBoolean(val: any): boolean {\n if (typeof val === 'string') {\n val = val.toLowerCase().trim();\n return val === 'true' || val === 'on' || val === '';\n }\n\n if (typeof val === 'number') {\n return val === 1;\n }\n\n return !!val;\n }\n\n abstract writeValue(value: any);\n\n abstract setLanguage(value: any);\n\n abstract setTheme(value: any);\n\n abstract setReadOnly(value: any);\n\n abstract setSuggestions(value: any);\n}\n","import { Injectable } from '@angular/core';\nimport {\n PoCodeEditorSuggestionList,\n PoCodeEditorRegisterableSuggestion\n} from './interfaces/po-code-editor-registerable-suggestion.interface';\n\n@Injectable({\n providedIn: 'root'\n})\nexport class PoCodeEditorSuggestionService {\n private suggestions: PoCodeEditorSuggestionList = {};\n constructor() {}\n\n public getSuggestion(language: string, newSuggestion: Array<PoCodeEditorRegisterableSuggestion>) {\n if (this.suggestions[language]) {\n const deduplicateSuggestions = this.deduplicateSuggestions(this.suggestions[language], newSuggestion);\n this.suggestions[language] = [...this.suggestions[language], ...deduplicateSuggestions];\n return deduplicateSuggestions;\n } else {\n return (this.suggestions[language] = [...newSuggestion]);\n }\n }\n\n private deduplicateSuggestions(\n originalSuggestions: Array<PoCodeEditorRegisterableSuggestion>,\n newSuggestions: Array<PoCodeEditorRegisterableSuggestion>\n ) {\n return newSuggestions.filter(\n newItem => !originalSuggestions.find(originalItem => originalItem['label'] === newItem['label'])\n );\n }\n}\n","import { Injectable } from '@angular/core';\n\nimport { PoCodeEditorRegisterable } from './interfaces/po-code-editor-registerable.interface';\nimport { PoCodeEditorRegisterableOptions } from './interfaces/po-code-editor-registerable-options.interface';\nimport { PoCodeEditorRegisterableSuggestionType } from './interfaces/po-code-editor-registerable-suggestion.interface';\n\n/**\n * @description\n *\n * Wrapper para registro de sintaxes customizadas para o po-code-editor.\n *\n * Para utilização do serviço de idiomas **PoCodeEditorRegister**,\n * deve-se importar o módulo PoCodeEditorModule mesmo já tendo importado\n * o módulo PoModule.\n * Na importação opcionalmente pode ser invocado o método **forRegister** informando um objeto para configuração.\n *\n * Exemplo de configuração:\n * ```\n * import { PoCodeEditorModule, PoCodeEditorRegisterable } from '@po-ui/ng-code-editor';\n *\n * declare const monaco: any; // Importante para usar configurações com tipos definidos pelo Monaco\n *\n * // A função `provideCompletionItems` precisa ser exportada para ser compatível com AOT.\n * export function provideCompletionItems() {\n * const suggestions = [{\n * label: 'terraform',\n * insertText: '#terraform language'\n * }, {\n * label: 'server',\n * insertText: 'server ${1:ip}'\n * }];\n *\n * return { suggestions: suggestions };\n * }\n *\n * const customEditor: PoCodeEditorRegisterable = {\n * language: 'terraform',\n * options: {\n * keywords: ['resource', 'provider', 'variable', 'output', 'module', 'true', 'false'],\n * operators: ['{', '}', '(', ')', '[', ']', '?', ':'],\n * symbols: /[=><!~?:&|+\\-*\\/\\^%]+/,\n * escapes: /\\\\(?:[abfnrtv\\\\\"']|x[0-9A-Fa-f]{1,4}|u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8})/,\n * tokenizer: {\n * ...\n * }\n * },\n * suggestions: { provideCompletionItems: provideCompletionItems }\n * };\n *\n * @NgModule({\n * declarations: [],\n * imports: [\n * PoModule,\n * PoCodeEditorModule.forRegister(customEditor)\n * ],\n * bootstrap: [AppComponent]\n * })\n * ```\n *\n * > As configurações para o registro de uma nova sintaxe no Monaco code editor podem ser encontradas em\n * > [**Monaco Editor**](https://microsoft.github.io/monaco-editor/playground.html#extending-language-services-custom-languages).\n */\n@Injectable({\n providedIn: 'root'\n})\nexport class PoCodeEditorRegister implements PoCodeEditorRegisterable {\n /** Sintaxe a ser registrada. */\n language: string;\n\n /** Opções da sintaxe para registro no po-code-editor. */\n options: PoCodeEditorRegisterableOptions;\n\n /** Lista de sugestões para a função de autocomplete (CTRL + SPACE). */\n suggestions?: PoCodeEditorRegisterableSuggestionType;\n}\n","import {\n inject,\n NgZone,\n DoCheck,\n Provider,\n ViewChild,\n Component,\n CSP_NONCE,\n ElementRef,\n forwardRef,\n AfterViewInit\n} from '@angular/core';\nimport { NG_VALUE_ACCESSOR } from '@angular/forms';\n\nimport { installMonacoCspCompat } from './po-code-editor-csp-compat';\nimport { PoCodeEditorRegister } from './po-code-editor-register.service';\nimport { PoCodeEditorBaseComponent } from './po-code-editor-base.component';\nimport { PoCodeEditorSuggestionService } from './po-code-editor-suggestion.service';\nimport { PoCodeEditorRegisterableSuggestion } from './interfaces/po-code-editor-registerable-suggestion.interface';\n\n// variáveis relacionadas ao Monaco\nlet loadedMonaco: boolean = false;\nlet loadPromise: Promise<void>;\n\ndeclare const monaco: any;\n// eslint-disable-next-line\ndeclare const require: any;\n\n/* istanbul ignore next */\nconst providers: Array<Provider> = [\n {\n provide: NG_VALUE_ACCESSOR,\n // eslint-disable-next-line\n useExisting: forwardRef(() => PoCodeEditorComponent),\n multi: true\n }\n];\n\n/**\n * @docsExtends PoCodeEditorBaseComponent\n *\n * @example\n *\n * <example name=\"po-code-editor-basic\" title=\"PO Code Editor Basic\">\n * <file name=\"sample-po-code-editor-basic/sample-po-code-editor-basic.component.html\"> </file>\n * <file name=\"sample-po-code-editor-basic/sample-po-code-editor-basic.component.ts\"> </file>\n * </example>\n *\n * <example name=\"po-code-editor-labs\" title=\"PO Code Editor Labs\">\n * <file name=\"sample-po-code-editor-labs/sample-po-code-editor-labs.component.html\"> </file>\n * <file name=\"sample-po-code-editor-labs/sample-po-code-editor-labs.component.ts\"> </file>\n * </example>\n *\n * <example name=\"po-code-editor-diff\" title=\"PO Code Editor - Diff\">\n * <file name=\"sample-po-code-editor-diff/sample-po-code-editor-diff.component.html\"> </file>\n * <file name=\"sample-po-code-editor-diff/sample-po-code-editor-diff.component.ts\"> </file>\n * </example>\n *\n * <example name=\"po-code-editor-terraform\" title=\"PO Code Editor - Terraform\">\n * <file name=\"sample-po-code-editor-terraform/sample-po-code-editor-terraform.component.html\"> </file>\n * <file name=\"sample-po-code-editor-terraform/sample-po-code-editor-terraform.component.ts\"> </file>\n * <file name=\"sample-po-code-editor-terraform/sample-po-code-editor-terraform.constant.ts\"> </file>\n * <file name=\"sample-po-code-editor-terraform/sample-po-code-editor-terraform.module.ts\"> </file>\n * </example>\n *\n * <example name=\"po-code-editor-suggestion\" title=\"PO Code Editor Suggestion\">\n * <file name=\"sample-po-code-editor-suggestion/sample-po-code-editor-suggestion.component.html\"> </file>\n * <file name=\"sample-po-code-editor-suggestion/sample-po-code-editor-suggestion.component.ts\"> </file>\n * </example>\n */\n@Component({\n selector: 'po-code-editor',\n templateUrl: './po-code-editor.component.html',\n providers,\n standalone: false\n})\nexport class PoCodeEditorComponent extends PoCodeEditorBaseComponent implements AfterViewInit, DoCheck {\n @ViewChild('editorContainer', { static: true }) editorContainer: ElementRef;\n\n canLoad = false;\n\n private readonly cspNonce: string | null = inject(CSP_NONCE, { optional: true });\n\n constructor(\n private zone: NgZone,\n private el: ElementRef,\n private poCodeEditorSuggestionService: PoCodeEditorSuggestionService,\n private codeEditorRegister?: PoCodeEditorRegister\n ) {\n super();\n }\n\n /* istanbul ignore next */\n ngAfterViewInit(): void {\n if (loadedMonaco) {\n /* istanbul ignore next */\n loadPromise.then(() => {\n setTimeout(() => {\n if (this.el.nativeElement.offsetWidth) {\n this.registerCustomLanguage();\n this.initMonaco(this.getOptions());\n } else {\n this.canLoad = true;\n }\n });\n });\n } else {\n loadedMonaco = true;\n loadPromise = new Promise<void>((resolve: any) => {\n if (!(<any>globalThis).require) {\n this.installCspCompat();\n\n const loaderScript: HTMLScriptElement = this.createLoaderScript();\n loaderScript.addEventListener('load', () => this.onGotAmdLoader(resolve));\n document.body.appendChild(loaderScript);\n }\n });\n }\n }\n\n /* istanbul ignore next */\n private onGotAmdLoader(resolve: () => void): void {\n (<any>globalThis).require.config(this.getLoaderConfig());\n (<any>globalThis).require(['vs/editor/editor.main'], () => {\n setTimeout(() => {\n if (this.el.nativeElement.offsetWidth) {\n this.registerCustomLanguage();\n this.initMonaco(this.getOptions());\n } else {\n this.canLoad = true;\n }\n resolve();\n });\n });\n }\n\n ngDoCheck() {\n if (this.canLoad && this.el.nativeElement.offsetWidth) {\n this.registerCustomLanguage();\n this.initMonaco(this.getOptions());\n this.canLoad = false;\n }\n }\n\n /* istanbul ignore next */\n monacoCreateModel(value: string) {\n return monaco.editor.createModel(value);\n }\n\n setValueInEditor() {\n if (this.showDiff) {\n setTimeout(() => {\n if (this.editor) {\n this.editor.setModel({\n original: this.monacoCreateModel(this.value),\n modified: this.monacoCreateModel(this.modifiedValue)\n });\n }\n });\n } else {\n setTimeout(() => {\n if (this.editor) {\n this.editor.setValue(this.value);\n }\n });\n }\n }\n\n setLanguage(language: string) {\n if (this.showDiff) {\n this.setMonacoLanguage(this.editor.getModel().original, language);\n this.setMonacoLanguage(this.editor.getModel().modified, language);\n } else {\n this.setMonacoLanguage(this.editor.getModel(), language);\n }\n }\n\n /* istanbul ignore next */\n setTheme(theme: string) {\n monaco.editor.setTheme(theme);\n }\n\n setReadOnly(readOnly: boolean) {\n this.editor.updateOptions({ readOnly: readOnly });\n }\n\n /* istanbul ignore next */\n setSuggestions(newSuggestions: Array<PoCodeEditorRegisterableSuggestion>, language = this.language) {\n if (!newSuggestions) {\n return;\n }\n\n const suggestions = this.poCodeEditorSuggestionService.getSuggestion(language, newSuggestions);\n\n monaco.languages.registerCompletionItemProvider(language, {\n provideCompletionItems: () => ({ suggestions })\n });\n }\n\n writeValue(value) {\n this.value = value && value instanceof Array ? value[0] : value;\n this.modifiedValue = value && value instanceof Array && value.length > 0 ? value[1] : '';\n this.setValueInEditor();\n }\n\n /* istanbul ignore next */\n private initMonaco(options: any): void {\n if (this.showDiff) {\n this.editor = monaco.editor.createDiffEditor(this.editorContainer.nativeElement, options);\n\n this.editor.setModel({\n original: monaco.editor.createModel(this.value),\n modified: monaco.editor.createModel(this.modifiedValue)\n });\n\n this.editor.onDidUpdateDiff((e: any) => {\n const original = this.editor.getModel().original.getValue();\n const modified = this.editor.getModel().modified.getValue();\n this.onChangePropagate([original, modified]);\n });\n } else {\n this.editor = monaco.editor.create(this.editorContainer.nativeElement, options);\n this.editor.setValue(this.value);\n this.editor.onDidChangeModelContent((e: any) => {\n const value = this.editor.getValue();\n this.onChangePropagate(value);\n this.zone.run(() => (this.value = value));\n });\n }\n setTimeout(() => {\n this.setLanguage(this.language);\n this.setSuggestions(this.suggestions);\n }, 500);\n }\n\n /* istanbul ignore next */\n private setMonacoLanguage(model, language) {\n monaco.editor.setModelLanguage(model, language);\n }\n\n private registerCustomLanguage() {\n if (this.codeEditorRegister.language) {\n monaco.languages.register({ id: this.codeEditorRegister.language });\n\n if (this.codeEditorRegister.options) {\n monaco.languages.setMonarchTokensProvider(this.codeEditorRegister.language, this.codeEditorRegister.options);\n }\n\n if (this.codeEditorRegister.suggestions) {\n this.setSuggestions(\n this.codeEditorRegister.suggestions.provideCompletionItems().suggestions,\n this.codeEditorRegister.language\n );\n }\n }\n }\n\n private installCspCompat(): void {\n if (this.cspNonce) {\n installMonacoCspCompat({\n nonce: this.cspNonce,\n monacoBaseUrl: new URL('./assets/monaco/vs/', document.baseURI).href\n });\n }\n }\n\n /**\n * Cria o `<script>` do loader do Monaco, aplicando o nonce da CSP quando configurado.\n */\n private createLoaderScript(): HTMLScriptElement {\n const loaderScript: HTMLScriptElement = document.createElement('script');\n loaderScript.type = 'text/javascript';\n loaderScript.src = './assets/monaco/vs/loader.js';\n\n if (this.cspNonce) {\n loaderScript.nonce = this.cspNonce;\n }\n\n return loaderScript;\n }\n\n /**\n * Retorna a configuração do loader AMD do Monaco. O loader aplica `cspNonce` nos scripts que carrega\n * (ex.: editor.main.js).\n */\n private getLoaderConfig(): { paths: { [key: string]: string }; cspNonce?: string } {\n const requireConfig: { paths: { [key: string]: string }; cspNonce?: string } = {\n paths: { 'vs': './assets/monaco/vs' }\n };\n\n if (this.cspNonce) {\n requireConfig.cspNonce = this.cspNonce;\n }\n\n return requireConfig;\n }\n}\n","<div #editorContainer [style.height]=\"height\"></div>\n","import { NgModule, ModuleWithProviders } from '@angular/core';\nimport { CommonModule } from '@angular/common';\n\nimport { PoCodeEditorComponent } from './po-code-editor.component';\nimport { PoCodeEditorRegister } from './po-code-editor-register.service';\nimport { PoCodeEditorRegisterable } from './interfaces/po-code-editor-registerable.interface';\n\n/**\n * @description\n *\n * Módulo do componente po-code-editor.\n */\n@NgModule({\n imports: [CommonModule],\n declarations: [PoCodeEditorComponent],\n exports: [PoCodeEditorComponent],\n providers: [PoCodeEditorRegister]\n})\nexport class PoCodeEditorModule {\n static forRegister(props: PoCodeEditorRegisterable): ModuleWithProviders<PoCodeEditorModule> {\n return {\n ngModule: PoCodeEditorModule,\n providers: [\n {\n provide: PoCodeEditorRegister,\n useValue: props\n }\n ]\n };\n }\n}\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './public-api';\n"],"names":["i1.PoCodeEditorSuggestionService","i2.PoCodeEditorRegister"],"mappings":";;;;;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;AA0BG;AAEH;AACO,MAAM,mBAAmB,GAAG,mBAAmB;AAEtD,MAAM,aAAa,GAAG,yBAAyB;AAE/C;;AAEG;AACH,MAAM,SAAS,GAAG,mBAAmB;AAErC;AACA,MAAM,qBAAqB,GAAG,mBAAmB;AAUjD;AACA,MAAM,eAAe,CAAA;AACU,IAAA,IAAA;AAA7B,IAAA,WAAA,CAA6B,IAAY,EAAA;QAAZ,IAAA,CAAA,IAAI,GAAJ,IAAI;IAAW;IAE5C,QAAQ,GAAA;QACN,OAAO,IAAI,CAAC,IAAI;IAClB;AACD;AAED;;AAEG;AACG,SAAU,sBAAsB,CAAC,IAAY,EAAA;AACjD,IAAA,IAAI,OAAO,IAAI,KAAK,QAAQ,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,QAAQ,CAAC,EAAE;AACxD,QAAA,OAAO,IAAI;IACb;IAEA,OAAO,IAAI,CAAC,UAAU,CAAC,SAAS,EAAE,GAAG,IAAI,GAAG,CAAC,UAAU,CAAC,qBAAqB,EAAE,KAAK,mBAAmB,CAAA,GAAA,CAAK,CAAC,CAAC;AAChH;AAEA;;AAEG;AACG,SAAU,iBAAiB,CAAC,IAAgC,EAAA;IAChE,IAAI,CAAC,IAAI,EAAE;QACT;IACF;AAEA,IAAA,IAAI,IAAI,CAA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kBAAkB,EAAA,CAAA;iEAFlB,CAAC,oBAAoB,CAAC,EAAA,OAAA,EAAA,CAHvB,YAAY,CAAA,EAAA,CAAA;;iFAKX,kBAAkB,EAAA,CAAA;cAN9B,QAAQ;AAAC,QAAA,IAAA,EAAA,CAAA;gBACR,OAAO,EAAE,CAAC,YAAY,CAAC;gBACvB,YAAY,EAAE,CAAC,qBAAqB,CAAC;gBACrC,OAAO,EAAE,CAAC,qBAAqB,CAAC;gBAChC,SAAS,EAAE,CAAC,oBAAoB;AACjC,aAAA;;AACY,CAAA,YAAA,EAAA,CAAA,OAAA,SAAA,KAAA,WAAA,IAAA,SAAA,KAAA,EAAA,CAAA,kBAAA,CAAA,kBAAkB,EAAA,EAAA,YAAA,EAAA,CAJd,qBAAqB,CAAA,EAAA,OAAA,EAAA,CAD1B,YAAY,aAEZ,qBAAqB,CAAA,EAAA,CAAA,CAAA,CAAA,CAAA,GAAA;;ACfjC;;AAEG;;;;"}
@@ -58,6 +58,53 @@ import * as i0 from "@angular/core";
58
58
  * ]
59
59
  * ...
60
60
  * </pre>
61
+ *
62
+ * #### Content Security Policy (CSP)
63
+ *
64
+ * O `po-code-editor` é compatível com políticas de segurança restritivas (CSP) baseadas em *nonce*, sem a necessidade
65
+ * de `'unsafe-inline'` em `script-src`, `style-src`, `style-src-elem` ou `style-src-attr`.
66
+ *
67
+ * O *nonce* é obtido do token `CSP_NONCE` do Angular, ou do atributo `ngCspNonce` em um elemento do `body`
68
+ * (normalmente o `<app-root>`). Não existe configuração específica do PO UI para isso e não é necessário chamar
69
+ * nenhum método ou informar nenhuma propriedade no componente.
70
+ *
71
+ * ```
72
+ * <!-- index.html -->
73
+ * <app-root ngCspNonce="NONCE_DA_REQUISICAO"></app-root>
74
+ * ```
75
+ *
76
+ * ou
77
+ *
78
+ * ```
79
+ * import { CSP_NONCE } from '@angular/core';
80
+ *
81
+ * providers: [{ provide: CSP_NONCE, useValue: nonceDaRequisicao }]
82
+ * ```
83
+ *
84
+ * Quando o *nonce* é informado, o `po-code-editor`:
85
+ *
86
+ * - aplica o *nonce* no `<script>` do `loader.js` do Monaco e o repassa à configuração do *loader* (`cspNonce`), que
87
+ * o aplica nos scripts que ele mesmo carrega;
88
+ * - aplica o *nonce* nos elementos `<style>` criados pelo Monaco, inclusive no *shadow DOM* do menu de contexto;
89
+ * - aplica, via CSSOM (`element.style`), os estilos que o Monaco define no atributo `style` dos elementos (posição das
90
+ * linhas, números de linha, seleção, decorações e indicadores do modo de comparação), pois o *nonce* não se aplica a
91
+ * atributos.
92
+ *
93
+ * Esses ajustes valem apenas para os elementos criados pelo Monaco e não alteram o restante da aplicação.
94
+ *
95
+ * **Pontos de atenção**
96
+ *
97
+ * - O valor informado deve ser o mesmo *nonce* enviado na política (`'nonce-...'`) da requisição atual.
98
+ * - O Monaco é carregado apenas uma vez por carregamento da página, quando o primeiro `po-code-editor` é exibido.
99
+ * Por isso, o *nonce* deve estar disponível antes disso.
100
+ * - O Monaco deve ser servido a partir de `assets/monaco/vs`, como configurado pelo `ng add @po-ui/ng-code-editor`.
101
+ * - Quando o *nonce* não é informado, o componente se comporta como antes: nenhum ajuste é aplicado.
102
+ * - A política também precisa permitir os demais recursos do Monaco (por exemplo, `worker-src` e `font-src`). Valide
103
+ * a política utilizada em um ambiente de teste antes de aplicá-la em produção.
104
+ *
105
+ * > **Atenção:** não utilize `'unsafe-inline'` em `style-src`, `style-src-elem` ou `style-src-attr` para contornar
106
+ * > bloqueios do editor. Quando a diretiva possui um *nonce*, o navegador ignora o `'unsafe-inline'`; e, caso o *nonce*
107
+ * > seja removido para que ele valha, qualquer estilo injetado passa a ser aceito, o que enfraquece a política.
61
108
  */
62
109
  export declare abstract class PoCodeEditorBaseComponent implements ControlValueAccessor {
63
110
  editor: any;
@@ -0,0 +1,51 @@
1
+ /**
2
+ * @docsPrivate
3
+ *
4
+ * Camada de compatibilidade entre o Monaco Editor (`0.44.0`) e Content-Security-Policy (CSP) baseada em *nonce*.
5
+ *
6
+ * O Monaco não oferece opção de *nonce* para os estilos que cria em tempo de execução. Sem esta camada, uma política
7
+ * sem `'unsafe-inline'` bloqueia:
8
+ *
9
+ * 1. os elementos `<style>` criados pelo Monaco (`document.createElement('style')`, inclusive no *shadow DOM* do menu
10
+ * de contexto). **Correção:** o *nonce* é aplicado somente nos `<style>` criados por código do Monaco;
11
+ * 2. os atributos `style` do HTML que o Monaco monta como texto (linhas, números de linha, seleção, decorações etc.).
12
+ * O *nonce* não se aplica a atributos. **Correção:** o HTML passa pelo *hook* público
13
+ * `MonacoEnvironment.createTrustedTypesPolicy`; o atributo `style` das tags é renomeado para um atributo de marcação e,
14
+ * logo após a inserção no DOM (na mesma tarefa), o valor é aplicado via CSSOM (`element.style.cssText`), que a CSP não
15
+ * bloqueia;
16
+ * 3. o `setAttribute('style', ...)` usado pelo Monaco (indicadores do modo diff). **Correção:** quando a chamada vem
17
+ * do Monaco, o valor é aplicado via CSSOM.
18
+ *
19
+ * Escopo:
20
+ * - A camada só é instalada quando a aplicação informa o `CSP_NONCE`, uma vez por página, antes do carregamento do
21
+ * Monaco.
22
+ * - Apenas o HTML produzido pelas políticas de Trusted Types do Monaco é convertido. O Monaco escapa `<`, `>` e `&` no
23
+ * conteúdo do usuário, então o conteúdo não consegue criar tags nem atributos. As demais atribuições de `innerHTML`
24
+ * da página não são alteradas.
25
+ * - Chamadas de `createElement` e `setAttribute` só são alteradas quando o código do Monaco está na pilha de chamadas
26
+ * (identificado pela URL da pasta `vs` do Monaco). Se essa identificação falhar, o comportamento é o anterior.
27
+ */
28
+ /** Atributo de marcação que substitui o `style` no HTML gerado pelo Monaco até a aplicação via CSSOM. */
29
+ export declare const PO_CSP_STYLE_MARKER = "data-po-csp-style";
30
+ export interface PoMonacoCspCompatOptions {
31
+ /** Nonce da política (o mesmo valor do token `CSP_NONCE`). */
32
+ nonce: string;
33
+ /** URL absoluta da pasta `vs` do Monaco, usada para identificar chamadas originadas no código do Monaco. */
34
+ monacoBaseUrl: string;
35
+ }
36
+ /**
37
+ * Renomeia o atributo `style` das tags do HTML para o atributo de marcação. O conteúdo de texto não é alterado.
38
+ */
39
+ export declare function rewriteStyleAttributes(html: string): string;
40
+ /**
41
+ * Aplica via CSSOM os estilos marcados no elemento e nos seus descendentes e remove o atributo de marcação.
42
+ */
43
+ export declare function applyMarkedStyles(root: Element | null | undefined): void;
44
+ /**
45
+ * Instala a camada de compatibilidade. A instalação é única por página: chamadas seguintes reaproveitam a primeira.
46
+ *
47
+ * @returns Função que desfaz a instalação (usada nos testes).
48
+ */
49
+ export declare function installMonacoCspCompat(options: PoMonacoCspCompatOptions): () => void;
50
+ /** Desfaz a instalação, se houver (usada nos testes). */
51
+ export declare function disposeMonacoCspCompat(): void;
@@ -1,8 +1,8 @@
1
- import { AfterViewInit, DoCheck, ElementRef, NgZone } from '@angular/core';
2
- import { PoCodeEditorBaseComponent } from './po-code-editor-base.component';
1
+ import { NgZone, DoCheck, ElementRef, AfterViewInit } from '@angular/core';
3
2
  import { PoCodeEditorRegister } from './po-code-editor-register.service';
4
- import { PoCodeEditorRegisterableSuggestion } from './interfaces/po-code-editor-registerable-suggestion.interface';
3
+ import { PoCodeEditorBaseComponent } from './po-code-editor-base.component';
5
4
  import { PoCodeEditorSuggestionService } from './po-code-editor-suggestion.service';
5
+ import { PoCodeEditorRegisterableSuggestion } from './interfaces/po-code-editor-registerable-suggestion.interface';
6
6
  import * as i0 from "@angular/core";
7
7
  /**
8
8
  * @docsExtends PoCodeEditorBaseComponent
@@ -43,8 +43,10 @@ export declare class PoCodeEditorComponent extends PoCodeEditorBaseComponent imp
43
43
  private codeEditorRegister?;
44
44
  editorContainer: ElementRef;
45
45
  canLoad: boolean;
46
+ private readonly cspNonce;
46
47
  constructor(zone: NgZone, el: ElementRef, poCodeEditorSuggestionService: PoCodeEditorSuggestionService, codeEditorRegister?: PoCodeEditorRegister);
47
48
  ngAfterViewInit(): void;
49
+ private onGotAmdLoader;
48
50
  ngDoCheck(): void;
49
51
  monacoCreateModel(value: string): any;
50
52
  setValueInEditor(): void;
@@ -56,6 +58,16 @@ export declare class PoCodeEditorComponent extends PoCodeEditorBaseComponent imp
56
58
  private initMonaco;
57
59
  private setMonacoLanguage;
58
60
  private registerCustomLanguage;
61
+ private installCspCompat;
62
+ /**
63
+ * Cria o `<script>` do loader do Monaco, aplicando o nonce da CSP quando configurado.
64
+ */
65
+ private createLoaderScript;
66
+ /**
67
+ * Retorna a configuração do loader AMD do Monaco. O loader aplica `cspNonce` nos scripts que carrega
68
+ * (ex.: editor.main.js).
69
+ */
70
+ private getLoaderConfig;
59
71
  static ɵfac: i0.ɵɵFactoryDeclaration<PoCodeEditorComponent, never>;
60
72
  static ɵcmp: i0.ɵɵComponentDeclaration<PoCodeEditorComponent, "po-code-editor", never, {}, {}, never, never, false, never>;
61
73
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@po-ui/ng-code-editor",
3
- "version": "19.39.28",
3
+ "version": "19.39.29",
4
4
  "description": "PO UI - Code Editor",
5
5
  "author": "PO UI",
6
6
  "license": "MIT",
@@ -11,8 +11,8 @@
11
11
  },
12
12
  "schematics": "./schematics/collection.json",
13
13
  "dependencies": {
14
- "@po-ui/ng-components": "19.39.28",
15
- "@po-ui/ng-schematics": "19.39.28",
14
+ "@po-ui/ng-components": "19.39.29",
15
+ "@po-ui/ng-schematics": "19.39.29",
16
16
  "monaco-editor": "0.44.0",
17
17
  "core-js": "^3.33.3",
18
18
  "intl": "^1.2.5",
@@ -22,7 +22,7 @@
22
22
  "@angular/common": "^19",
23
23
  "@angular/core": "^19",
24
24
  "@angular/forms": "^19",
25
- "@po-ui/ng-components": "19.39.28",
25
+ "@po-ui/ng-components": "19.39.29",
26
26
  "monaco-editor": "0.44.0",
27
27
  "zone.js": "~0.15.0"
28
28
  },
@@ -31,7 +31,7 @@ function default_1(options) {
31
31
  }
32
32
  function addPoPackageAndInstall() {
33
33
  return (tree, context) => {
34
- (0, package_config_1.addPackageToPackageJson)(tree, '@po-ui/ng-code-editor', '19.39.28');
34
+ (0, package_config_1.addPackageToPackageJson)(tree, '@po-ui/ng-code-editor', '19.39.29');
35
35
  // install packages
36
36
  context.addTask(new tasks_1.NodePackageInstallTask());
37
37
  };
Binary file