@cagov/ca-ds 1.0.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. package/README.md +43 -26
  2. package/THIRD-PARTY-LICENSES.txt +690 -0
  3. package/ca-ds.js +48390 -0
  4. package/package.json +5 -31
  5. package/bin/ca-ds.js +0 -5
  6. package/src/cli/add.js +0 -134
  7. package/src/cli/build.js +0 -15
  8. package/src/cli/diff.js +0 -39
  9. package/src/cli/eject.js +0 -112
  10. package/src/cli/exit.js +0 -22
  11. package/src/cli/format.js +0 -52
  12. package/src/cli/init.js +0 -148
  13. package/src/cli/install.js +0 -178
  14. package/src/cli/items.js +0 -10
  15. package/src/cli/login.js +0 -331
  16. package/src/cli/main.js +0 -108
  17. package/src/cli/new.js +0 -230
  18. package/src/cli/outdated.js +0 -74
  19. package/src/cli/pack.js +0 -75
  20. package/src/cli/preview.js +0 -31
  21. package/src/cli/publish.js +0 -295
  22. package/src/cli/pull.js +0 -208
  23. package/src/cli/remote.js +0 -52
  24. package/src/cli/remove.js +0 -69
  25. package/src/cli/update.js +0 -223
  26. package/src/cli/validate.js +0 -131
  27. package/src/lib/browser.js +0 -12
  28. package/src/lib/build.js +0 -249
  29. package/src/lib/bundle.js +0 -148
  30. package/src/lib/catalog.js +0 -44
  31. package/src/lib/checks.js +0 -31
  32. package/src/lib/collection.js +0 -65
  33. package/src/lib/emblem.js +0 -29
  34. package/src/lib/fixtures.js +0 -59
  35. package/src/lib/floor.js +0 -79
  36. package/src/lib/glyph.js +0 -148
  37. package/src/lib/image.js +0 -138
  38. package/src/lib/json-text.js +0 -213
  39. package/src/lib/keys.js +0 -322
  40. package/src/lib/links.js +0 -321
  41. package/src/lib/markdown.js +0 -408
  42. package/src/lib/merge.js +0 -93
  43. package/src/lib/pack.js +0 -30
  44. package/src/lib/page-schema.js +0 -368
  45. package/src/lib/page.js +0 -372
  46. package/src/lib/patch.js +0 -9
  47. package/src/lib/regions.js +0 -173
  48. package/src/lib/registry.js +0 -371
  49. package/src/lib/release.js +0 -119
  50. package/src/lib/repoints.js +0 -120
  51. package/src/lib/resolve.js +0 -32
  52. package/src/lib/schema.js +0 -28
  53. package/src/lib/serial.js +0 -4
  54. package/src/lib/serialize.js +0 -444
  55. package/src/lib/structured.js +0 -72
  56. package/src/lib/system.js +0 -13
  57. package/src/lib/targets.js +0 -85
  58. package/src/lib/terms.js +0 -11
  59. package/src/lib/token-view.js +0 -289
  60. package/src/lib/tokens.js +0 -247
  61. package/src/lib/version.js +0 -34
  62. package/src/preview/frame.js +0 -75
  63. package/src/preview/pages.js +0 -128
  64. package/src/preview/screenshots.js +0 -72
  65. package/src/preview/server.js +0 -378
  66. package/src/preview/shell.js +0 -153
  67. package/src/schema/a11y.schema.json +0 -56
  68. package/src/schema/collection.lock.schema.json +0 -58
  69. package/src/schema/collection.schema.json +0 -65
  70. package/src/schema/composition.schema.json +0 -98
  71. package/src/schema/contract.schema.json +0 -116
  72. package/src/schema/interface.schema.json +0 -257
  73. package/src/schema/item.schema.json +0 -362
  74. package/src/schema/release.schema.json +0 -39
  75. package/src/schema/system.schema.json +0 -75
  76. package/src/schema/variants.schema.json +0 -60
  77. package/src/validate/collection.js +0 -19
  78. package/src/validate/collisions.js +0 -124
  79. package/src/validate/context.js +0 -357
  80. package/src/validate/facts.js +0 -253
  81. package/src/validate/files.js +0 -103
  82. package/src/validate/findings.js +0 -19
  83. package/src/validate/glyphs.js +0 -126
  84. package/src/validate/html.js +0 -215
  85. package/src/validate/imports.js +0 -29
  86. package/src/validate/index.js +0 -75
  87. package/src/validate/item.js +0 -47
  88. package/src/validate/links.js +0 -113
  89. package/src/validate/manifest.js +0 -147
  90. package/src/validate/media.js +0 -65
  91. package/src/validate/page.js +0 -74
  92. package/src/validate/prefixes.js +0 -58
  93. package/src/validate/relations.js +0 -310
  94. package/src/validate/release.js +0 -109
  95. package/src/validate/skill.js +0 -122
  96. package/src/validate/structured.js +0 -335
  97. package/src/validate/tasc.js +0 -80
  98. package/src/validate/template.js +0 -129
  99. package/src/validate/tokens.js +0 -154
  100. package/src/validate/zip.js +0 -40
  101. /package/{src/preview/preview.css → preview.css} +0 -0
@@ -1,408 +0,0 @@
1
- // No DOM and no Node API, so the browser bundle shares it. The parse must match service/docs/render.js.
2
- // Each textblock takes the lowest escape level that parses back the same, so a source with no backslash
3
- // round-trips unchanged.
4
-
5
- import MarkdownIt from 'markdown-it';
6
- import { Schema, Fragment } from 'prosemirror-model';
7
- import { MarkdownParser, MarkdownSerializer, MarkdownSerializerState } from 'prosemirror-markdown';
8
-
9
- const ALIGNS = ['left', 'center', 'right'];
10
-
11
- const cellAttrs = { align: { default: null } };
12
- const cellDom = (tag) => (node) => [tag, node.attrs.align ? { style: `text-align: ${node.attrs.align}` } : {}, 0];
13
- const alignOf = (dom) => {
14
- const align = dom.style?.textAlign;
15
- return { align: ALIGNS.includes(align) ? align : null };
16
- };
17
-
18
- // toDOM and parseDOM serve the editor's view and paste. The round trip never calls them.
19
- export const schema = new Schema({
20
- nodes: {
21
- doc: { content: 'frontmatter? block+' },
22
- frontmatter: {
23
- attrs: { text: { default: '' } },
24
- atom: true,
25
- selectable: true,
26
- defining: true,
27
- toDOM: (node) => ['pre', { class: 'frontmatter' }, node.attrs.text],
28
- },
29
- paragraph: { content: 'inline*', group: 'block', toDOM: () => ['p', 0], parseDOM: [{ tag: 'p' }] },
30
- heading: {
31
- attrs: { level: { default: 2 } },
32
- content: 'inline*',
33
- group: 'block',
34
- defining: true,
35
- toDOM: (node) => [`h${node.attrs.level}`, 0],
36
- parseDOM: [1, 2, 3, 4, 5, 6].map((level) => ({ tag: `h${level}`, attrs: { level } })),
37
- },
38
- blockquote: { content: 'block+', group: 'block', defining: true, toDOM: () => ['blockquote', 0], parseDOM: [{ tag: 'blockquote' }] },
39
- code_block: {
40
- attrs: { params: { default: '' } },
41
- content: 'text*',
42
- marks: '',
43
- group: 'block',
44
- code: true,
45
- defining: true,
46
- toDOM: (node) => ['pre', node.attrs.params ? { 'data-params': node.attrs.params } : {}, ['code', 0]],
47
- parseDOM: [{ tag: 'pre', preserveWhitespace: 'full', getAttrs: (dom) => ({ params: dom.getAttribute('data-params') ?? '' }) }],
48
- },
49
- horizontal_rule: { group: 'block', toDOM: () => ['hr'], parseDOM: [{ tag: 'hr' }] },
50
- bullet_list: {
51
- attrs: { tight: { default: true } },
52
- content: 'list_item+',
53
- group: 'block',
54
- toDOM: () => ['ul', 0],
55
- parseDOM: [{ tag: 'ul' }],
56
- },
57
- ordered_list: {
58
- attrs: { order: { default: 1 }, tight: { default: true } },
59
- content: 'list_item+',
60
- group: 'block',
61
- toDOM: (node) => ['ol', node.attrs.order === 1 ? {} : { start: node.attrs.order }, 0],
62
- parseDOM: [{ tag: 'ol', getAttrs: (dom) => ({ order: dom.hasAttribute('start') ? Number(dom.getAttribute('start')) : 1 }) }],
63
- },
64
- list_item: { content: 'paragraph block*', defining: true, toDOM: () => ['li', 0], parseDOM: [{ tag: 'li' }] },
65
- table: { content: 'table_row+', group: 'block', isolating: true, toDOM: () => ['table', ['tbody', 0]], parseDOM: [{ tag: 'table' }] },
66
- table_row: { content: '(table_header | table_cell)+', toDOM: () => ['tr', 0], parseDOM: [{ tag: 'tr' }] },
67
- table_header: { attrs: cellAttrs, content: 'inline*', isolating: true, toDOM: cellDom('th'), parseDOM: [{ tag: 'th', getAttrs: alignOf }] },
68
- table_cell: { attrs: cellAttrs, content: 'inline*', isolating: true, toDOM: cellDom('td'), parseDOM: [{ tag: 'td', getAttrs: alignOf }] },
69
- text: { group: 'inline' },
70
- image: {
71
- attrs: { src: {}, alt: { default: null }, title: { default: null } },
72
- inline: true,
73
- group: 'inline',
74
- draggable: true,
75
- toDOM: (node) => ['img', { src: node.attrs.src, alt: node.attrs.alt, title: node.attrs.title }],
76
- parseDOM: [{ tag: 'img[src]', getAttrs: (dom) => ({ src: dom.getAttribute('src'), alt: dom.getAttribute('alt'), title: dom.getAttribute('title') }) }],
77
- },
78
- hard_break: { inline: true, group: 'inline', selectable: false, toDOM: () => ['br'], parseDOM: [{ tag: 'br' }] },
79
- },
80
- marks: {
81
- link: {
82
- attrs: { href: {}, title: { default: null } },
83
- inclusive: false,
84
- toDOM: (mark) => ['a', { href: mark.attrs.href, title: mark.attrs.title }, 0],
85
- parseDOM: [{ tag: 'a[href]', getAttrs: (dom) => ({ href: dom.getAttribute('href'), title: dom.getAttribute('title') }) }],
86
- },
87
- em: { toDOM: () => ['em', 0], parseDOM: [{ tag: 'em' }, { tag: 'i' }] },
88
- strong: { toDOM: () => ['strong', 0], parseDOM: [{ tag: 'strong' }, { tag: 'b' }] },
89
- strike: { toDOM: () => ['s', 0], parseDOM: [{ tag: 's' }, { tag: 'del' }] },
90
- code: { code: true, toDOM: () => ['code', 0], parseDOM: [{ tag: 'code' }] },
91
- },
92
- });
93
-
94
- // Links keep the URL their source spells, with no percent-encoding.
95
- const tokenizer = new MarkdownIt({ html: false, linkify: false, typographer: false });
96
- tokenizer.normalizeLink = (url) => url;
97
- tokenizer.normalizeLinkText = (url) => url;
98
-
99
- const listIsTight = (tokens, i) => {
100
- for (let k = i + 1; k < tokens.length; k++) if (tokens[k].type !== 'list_item_open') return tokens[k].hidden;
101
- return false;
102
- };
103
- const alignFrom = (token) => {
104
- const m = /text-align:\s*(\w+)/.exec(token.attrGet('style') ?? '');
105
- return { align: m && ALIGNS.includes(m[1]) ? m[1] : null };
106
- };
107
-
108
- const parser = new MarkdownParser(schema, tokenizer, {
109
- blockquote: { block: 'blockquote' },
110
- paragraph: { block: 'paragraph' },
111
- list_item: { block: 'list_item' },
112
- bullet_list: { block: 'bullet_list', getAttrs: (_, tokens, i) => ({ tight: listIsTight(tokens, i) }) },
113
- ordered_list: { block: 'ordered_list', getAttrs: (tok, tokens, i) => ({ order: Number(tok.attrGet('start')) || 1, tight: listIsTight(tokens, i) }) },
114
- heading: { block: 'heading', getAttrs: (tok) => ({ level: Number(tok.tag.slice(1)) }) },
115
- code_block: { block: 'code_block', noCloseToken: true },
116
- fence: { block: 'code_block', getAttrs: (tok) => ({ params: tok.info || '' }), noCloseToken: true },
117
- hr: { node: 'horizontal_rule' },
118
- table: { block: 'table' },
119
- thead: { ignore: true },
120
- tbody: { ignore: true },
121
- tr: { block: 'table_row' },
122
- th: { block: 'table_header', getAttrs: alignFrom },
123
- td: { block: 'table_cell', getAttrs: alignFrom },
124
- image: {
125
- node: 'image',
126
- getAttrs: (tok) => ({ src: tok.attrGet('src'), title: tok.attrGet('title') || null, alt: tok.children?.[0]?.content || null }),
127
- },
128
- hardbreak: { node: 'hard_break' },
129
- em: { mark: 'em' },
130
- strong: { mark: 'strong' },
131
- s: { mark: 'strike' },
132
- link: { mark: 'link', getAttrs: (tok) => ({ href: tok.attrGet('href'), title: tok.attrGet('title') || null }) },
133
- code_inline: { mark: 'code', noCloseToken: true },
134
- });
135
-
136
- // A hand-written file may carry a BOM, CRLF, or no blank line after the closing fence.
137
- const FRONTMATTER = /^\uFEFF?---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)(?:\r?\n)?/;
138
-
139
- export function splitFrontmatter(text) {
140
- const m = FRONTMATTER.exec(text);
141
- return m ? { frontmatter: m[1].replace(/\r\n/g, '\n'), body: text.slice(m[0].length) } : { frontmatter: null, body: text };
142
- }
143
-
144
- export function parseMarkdown(text) {
145
- const { frontmatter, body } = splitFrontmatter(text);
146
- const doc = parser.parse(body);
147
- if (frontmatter === null) return doc;
148
- return schema.node('doc', null, [schema.node('frontmatter', { text: frontmatter }), ...(doc.content.content)]);
149
- }
150
-
151
- // Escape levels: 0 none, 1 a backslash before each markup character, 2 prosemirror-markdown's own.
152
- const MARKUP = /[\\`*_~[\]<>!&|]/g;
153
- const LINE_START = /^(\s*)(\d*)([-+*>#.)])/;
154
- const escapeMarkup = (text, start) => {
155
- const out = text.replace(MARKUP, '\\$&');
156
- return start ? out.replace(LINE_START, (m, space, digits, mark) => `${space}${digits}\\${mark}`) : out;
157
- };
158
-
159
- function writeText(state, node) {
160
- const level = state.escapeLevel ?? 0;
161
- if (state.inAutolink || level === 0) state.text(node.text, false);
162
- else if (level === 1) state.text(escapeMarkup(node.text, state.atBlockStart && !state.inCell), false);
163
- else state.text(node.text, true);
164
- }
165
-
166
- function destination(url) {
167
- if (/[\s<>]/.test(url)) return `<${url.replace(/[<>]/g, '\\$&')}>`;
168
- let depth = 0;
169
- for (const ch of url) {
170
- depth += ch === '(' ? 1 : ch === ')' ? -1 : 0;
171
- if (depth < 0) break;
172
- }
173
- return depth === 0 ? url : url.replace(/[()]/g, '\\$&');
174
- }
175
-
176
- const isList = (node) => node.type.name === 'bullet_list' || node.type.name === 'ordered_list';
177
-
178
- const blankInside = (item) => item.childCount > 2 || (item.childCount === 2 && !isList(item.child(1)));
179
-
180
- // A list right after one of its type takes the other marker, `*` or `1)`, since the same one would join them.
181
- function renderList(state, node, delim, firstDelim) {
182
- const items = node.content.content;
183
- const loose = !node.attrs.tight || items.some(blankInside);
184
- const between = loose && !items.some(blankInside) ? 2 : 1;
185
- state.alternates ??= new WeakMap();
186
- const follows = state.closed && state.closed.type === node.type;
187
- const alt = follows ? !state.alternates.get(state.closed) : false;
188
- state.alternates.set(node, alt);
189
- if (follows) state.flushClose(2);
190
- else if (state.inTightItem) state.flushClose(1);
191
- const before = state.inTightItem;
192
- items.forEach((item, i) => {
193
- if (i > 0) state.flushClose(between);
194
- state.wrapBlock(delim, firstDelim(i, alt), node, () => {
195
- item.forEach((child, _, k) => {
196
- state.inTightItem = !loose || (k === 1 && isList(child));
197
- if (k > 0) state.flushClose(state.inTightItem ? 1 : 2);
198
- state.render(child, item, k);
199
- });
200
- });
201
- });
202
- state.inTightItem = before;
203
- }
204
-
205
- function fenceFor(text) {
206
- const runs = text.match(/`{3,}/g);
207
- return runs ? '`'.repeat(Math.max(...runs.map((r) => r.length)) + 1) : '```';
208
- }
209
-
210
- // An empty line takes no indent, so a blank line in a list's fence carries no trailing spaces.
211
- function writeRaw(state, text) {
212
- text.split('\n').forEach((line, i) => {
213
- if (i > 0) state.out += '\n';
214
- if (line === '') state.flushClose();
215
- else state.write(line);
216
- });
217
- }
218
-
219
- const nodes = {
220
- frontmatter(state, node) {
221
- state.write(`---\n${node.attrs.text}\n---`);
222
- state.closeBlock(node);
223
- },
224
- blockquote(state, node) {
225
- state.wrapBlock('> ', null, node, () => state.renderContent(node));
226
- },
227
- code_block(state, node) {
228
- const fence = fenceFor(node.textContent);
229
- state.write(`${fence}${node.attrs.params || ''}\n`);
230
- writeRaw(state, node.textContent);
231
- state.ensureNewLine();
232
- state.write(fence);
233
- state.closeBlock(node);
234
- },
235
- heading(state, node) {
236
- state.write(`${'#'.repeat(node.attrs.level)} `);
237
- inline(state, node, (s) => `${'#'.repeat(node.attrs.level)} ${s}`, false);
238
- state.closeBlock(node);
239
- },
240
- horizontal_rule(state, node) {
241
- state.write('---');
242
- state.closeBlock(node);
243
- },
244
- bullet_list(state, node) {
245
- renderList(state, node, ' ', (i, alt) => (alt ? '* ' : '- '));
246
- },
247
- ordered_list(state, node) {
248
- const start = node.attrs.order ?? 1;
249
- const width = String(start + node.childCount - 1).length;
250
- renderList(state, node, ' '.repeat(width + 2), (i, alt) => `${start + i}${alt ? ')' : '.'} `.padEnd(width + 2));
251
- },
252
- paragraph(state, node) {
253
- inline(state, node, (s) => s);
254
- state.closeBlock(node);
255
- },
256
- table(state, node) {
257
- node.forEach((row, _, r) => {
258
- if (r > 0) state.ensureNewLine();
259
- state.write('|');
260
- row.forEach((cell) => {
261
- state.write(' ');
262
- if (cell.content.size > 0) {
263
- state.inCell = true;
264
- inline(state, cell, (s) => `| ${s} |\n|---|`, false);
265
- state.inCell = false;
266
- state.write(' ');
267
- }
268
- state.write('|');
269
- });
270
- if (r === 0) {
271
- state.ensureNewLine();
272
- const seps = [];
273
- row.forEach((cell) => {
274
- const { align } = cell.attrs;
275
- seps.push(align === 'left' ? ':---' : align === 'center' ? ':---:' : align === 'right' ? '---:' : '---');
276
- });
277
- state.write(`|${seps.join('|')}|`);
278
- }
279
- });
280
- state.closeBlock(node);
281
- },
282
- image(state, node) {
283
- const alt = node.attrs.alt ?? '';
284
- state.write(`![${alt.replace(/[[\]\\]/g, '\\$&')}](${destination(node.attrs.src)}${node.attrs.title ? ` "${node.attrs.title.replace(/"/g, '\\"')}"` : ''})`);
285
- },
286
- hard_break(state, node, parent, index) {
287
- for (let i = index + 1; i < parent.childCount; i++) {
288
- if (parent.child(i).type !== node.type) {
289
- state.write('\\\n');
290
- return;
291
- }
292
- }
293
- },
294
- text: writeText,
295
- };
296
-
297
- const marks = {
298
- em: { open: '*', close: '*', mixable: true, expelEnclosingWhitespace: true },
299
- strong: { open: '**', close: '**', mixable: true, expelEnclosingWhitespace: true },
300
- strike: { open: '~~', close: '~~', mixable: true, expelEnclosingWhitespace: true },
301
- link: {
302
- open: '[',
303
- close: (state, mark) => `](${destination(mark.attrs.href)}${mark.attrs.title ? ` "${mark.attrs.title.replace(/"/g, '\\"')}"` : ''})`,
304
- mixable: true,
305
- },
306
- code: {
307
- open: (_state, _mark, parent, index) => backticks(parent.child(index), -1),
308
- close: (_state, _mark, parent, index) => backticks(parent.child(index - 1), 1),
309
- escape: false,
310
- },
311
- };
312
-
313
- function backticks(node, side) {
314
- let len = 0;
315
- if (node.isText) for (const run of node.text.match(/`+/g) ?? []) len = Math.max(len, run.length);
316
- const ticks = '`'.repeat(len + 1);
317
- if (len === 0) return ticks;
318
- return side > 0 ? ` ${ticks}` : `${ticks} `;
319
- }
320
-
321
- const serializer = new MarkdownSerializer(nodes, marks, { strict: true });
322
-
323
- function renderAlone(node, level, inCell, fromStart) {
324
- const state = new MarkdownSerializerState(nodes, marks, { tightLists: false, hardBreakNodeName: 'hard_break', strict: true });
325
- state.escapeLevel = level;
326
- state.inCell = inCell;
327
- state.renderInline(node, fromStart);
328
- return state.out;
329
- }
330
-
331
- function parsesBack(node, source) {
332
- let doc;
333
- try {
334
- doc = parser.parse(source);
335
- } catch {
336
- return false;
337
- }
338
- let found = null;
339
- doc.descendants((n) => {
340
- if (found) return false;
341
- if (n.isTextblock) {
342
- found = n;
343
- return false;
344
- }
345
- return true;
346
- });
347
- const content = found?.content ?? Fragment.empty;
348
- return content.eq(node.content);
349
- }
350
-
351
- // Drops the whitespace markdown can't hold.
352
- function tidy(node) {
353
- const children = [];
354
- node.forEach((child) => children.push(child.isText ? child.type.schema.text(child.text.replace(/\n/g, ' '), child.marks) : child));
355
- const trim = (i, side) => {
356
- const child = children[i];
357
- if (!child?.isText) return;
358
- const text = side < 0 ? child.text.replace(/^\s+/, '') : child.text.replace(/\s+$/, '');
359
- children[i] = text ? child.withText(text) : null;
360
- };
361
- children.forEach((child, i) => {
362
- if (child?.type.name !== 'hard_break') return;
363
- trim(i - 1, 1);
364
- trim(i + 1, -1);
365
- });
366
- trim(0, -1);
367
- trim(children.length - 1, 1);
368
- const kept = children.filter(Boolean);
369
- return kept.length === node.childCount && kept.every((c, i) => c === node.child(i)) ? node : node.copy(Fragment.fromArray(kept));
370
- }
371
-
372
- function inline(state, given, context, fromStart = true) {
373
- const node = tidy(given);
374
- const inCell = state.inCell === true;
375
- let level = 0;
376
- while (level < 2 && !parsesBack(node, context(renderAlone(node, level, inCell, fromStart)))) level += 1;
377
- const before = state.escapeLevel;
378
- state.escapeLevel = level;
379
- state.renderInline(node, fromStart);
380
- state.escapeLevel = before;
381
- }
382
-
383
- export function serializeMarkdown(doc) {
384
- const out = serializer.serialize(doc, { tightLists: false });
385
- return out === '' ? '' : `${out.replace(/\n+$/, '')}\n`;
386
- }
387
-
388
- export const normalizeMarkdown = (text) => serializeMarkdown(parseMarkdown(text));
389
-
390
- export function firstDifference(expected, actual) {
391
- if (expected === actual) return null;
392
- const a = expected.split('\n');
393
- const b = actual.split('\n');
394
- for (let i = 0; i < Math.max(a.length, b.length); i++) {
395
- if (a[i] !== b[i]) return { line: i + 1, expected: a[i] ?? null, actual: b[i] ?? null };
396
- }
397
- return { line: a.length, expected: a.at(-1), actual: b.at(-1) };
398
- }
399
-
400
- export function roundTrip(text) {
401
- let normalized;
402
- try {
403
- normalized = normalizeMarkdown(text);
404
- } catch (error) {
405
- return { normalized: null, difference: null, error: error.message };
406
- }
407
- return { normalized, difference: firstDifference(text, normalized) };
408
- }
package/src/lib/merge.js DELETED
@@ -1,93 +0,0 @@
1
- // base is the file as installed, ours the local file, theirs the update's; each bytes or null when absent.
2
- // A JSON file merges by key path, an array as one value, and never takes markers, which break every reader.
3
-
4
- import { isDeepStrictEqual } from 'node:util';
5
- import { diff3Merge } from 'node-diff3';
6
- import { editedJson } from './json-text.js';
7
-
8
- const encoder = new TextEncoder();
9
- const decoder = new TextDecoder('utf-8', { fatal: true });
10
-
11
- export function isBinary(bytes) {
12
- if (bytes.includes(0)) return true;
13
- try {
14
- decoder.decode(bytes);
15
- return false;
16
- } catch {
17
- return true;
18
- }
19
- }
20
-
21
- const same = (a, b) => (a === null || b === null ? a === b : Buffer.from(a.buffer, a.byteOffset, a.byteLength).equals(b));
22
- const lines = (text) => (text === '' ? [] : text.split(/(?<=\n)/));
23
- const block = (part) => {
24
- const text = part.join('');
25
- return text === '' || text.endsWith('\n') ? text : `${text}\n`;
26
- };
27
-
28
- export function mergeText(base, ours, theirs, labels = { ours: 'local', theirs: 'upstream' }) {
29
- let text = '';
30
- let conflicts = 0;
31
- for (const region of diff3Merge(lines(ours), lines(base), lines(theirs), { excludeFalseConflicts: true })) {
32
- if (region.ok) {
33
- text += region.ok.join('');
34
- } else {
35
- conflicts += 1;
36
- text += `<<<<<<< ${labels.ours}\n${block(region.conflict.a)}=======\n${block(region.conflict.b)}>>>>>>> ${labels.theirs}\n`;
37
- }
38
- }
39
- return { text, conflicts };
40
- }
41
-
42
- const MISSING = Symbol('missing');
43
- const isObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
44
- const pointer = (path) => (path.length ? path.map((k) => `/${k.replaceAll('~', '~0').replaceAll('/', '~1')}`).join('') : '');
45
-
46
- // base is undefined when the file is new on both sides. conflicts are JSON Pointers, '' for the whole document.
47
- export function mergeJson(base, ours, theirs) {
48
- const conflicts = [];
49
- const walk = (o, a, b, path) => {
50
- if (isDeepStrictEqual(a, b)) return a;
51
- if (isDeepStrictEqual(a, o)) return b;
52
- if (isDeepStrictEqual(b, o)) return a;
53
- if (isObject(a) && isObject(b) && (isObject(o) || o === MISSING)) {
54
- const from = isObject(o) ? o : {};
55
- const out = {};
56
- for (const key of new Set([...Object.keys(b), ...Object.keys(a)])) {
57
- const at = (x) => (Object.hasOwn(x, key) ? x[key] : MISSING);
58
- const value = walk(at(from), at(a), at(b), [...path, key]);
59
- if (value !== MISSING) out[key] = value;
60
- }
61
- return out;
62
- }
63
- conflicts.push(pointer(path));
64
- return a;
65
- };
66
- const value = walk(base === undefined ? MISSING : base, ours, theirs, []);
67
- return { value, conflicts };
68
- }
69
-
70
- const parse = (bytes) => {
71
- try {
72
- return { ok: true, value: JSON.parse(decoder.decode(bytes)) };
73
- } catch {
74
- return { ok: false };
75
- }
76
- };
77
-
78
- export function mergeFile(path, { base, ours, theirs }, labels) {
79
- if (same(ours, base)) return { outcome: same(theirs, base) ? 'kept' : 'updated', bytes: theirs };
80
- if (same(theirs, base) || same(ours, theirs)) return { outcome: 'kept', bytes: ours };
81
- if (ours === null || theirs === null) return { outcome: 'stop', reason: 'deleted' };
82
- if ([base, ours, theirs].some((b) => b !== null && isBinary(b))) return { outcome: 'stop', reason: 'binary' };
83
- if (path.endsWith('.json')) {
84
- const [o, a, b] = [base, ours, theirs].map((x) => (x === null ? { ok: true, value: undefined } : parse(x)));
85
- if (!o.ok || !a.ok || !b.ok) return { outcome: 'stop', reason: 'unparsable' };
86
- const { value, conflicts } = mergeJson(o.value, a.value, b.value);
87
- if (conflicts.length) return { outcome: 'stop', reason: 'json', keys: conflicts };
88
- const text = isObject(value) ? editedJson(decoder.decode(theirs), value) : `${JSON.stringify(value, null, 2)}\n`;
89
- return { outcome: 'merged', bytes: encoder.encode(text) };
90
- }
91
- const { text, conflicts } = mergeText(base === null ? '' : decoder.decode(base), decoder.decode(ours), decoder.decode(theirs), labels);
92
- return { outcome: conflicts ? 'conflict' : 'merged', bytes: encoder.encode(text), conflicts };
93
- }
package/src/lib/pack.js DELETED
@@ -1,30 +0,0 @@
1
- import { readFileSync } from 'node:fs';
2
- import { extname, join } from 'node:path';
3
- import { createHash } from 'node:crypto';
4
- import { zipSync } from 'fflate';
5
-
6
- // Fixed so the same files zip to the same bytes. ZIP stores local time, and 1980 is its earliest date.
7
- const EPOCH = new Date(1980, 0, 1);
8
-
9
- // Already compressed, so stored at level 0.
10
- const STORED = new Set(['.png', '.webp', '.jpg', '.jpeg', '.gif']);
11
-
12
- export function itemFiles(item) {
13
- const paths = ['item.json', ...item.present].sort();
14
- return new Map(paths.map((p) => [p, readFileSync(join(item.dir, p))]));
15
- }
16
-
17
- export function zipName(manifest) {
18
- return `${manifest.name.replace('/', '-')}-${manifest.version}.zip`;
19
- }
20
-
21
- export function zip(files) {
22
- const entries = files instanceof Map ? [...files] : Object.entries(files);
23
- entries.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
24
- const options = (path) => (STORED.has(extname(path).toLowerCase()) ? { mtime: EPOCH, level: 0 } : { mtime: EPOCH });
25
- return zipSync(Object.fromEntries(entries.map(([path, bytes]) => [path, [bytes, options(path)]])));
26
- }
27
-
28
- export function sha256(bytes) {
29
- return createHash('sha256').update(bytes).digest('hex');
30
- }