@pairdraw/emit 0.0.0-stage → 0.16.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Danila Poyarkov and OpenPencil contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,41 @@
1
- # Temporary Holding Version
1
+ # @pairdraw/emit
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ How Pairdraw's exporters emit source code. Build JavaScript, TypeScript, and JSX as ESTree nodes and print them with [esrap](https://github.com/sveltejs/esrap), instead of concatenating strings.
4
+
5
+ ```ts
6
+ import { jsx } from '@pairdraw/emit'
7
+
8
+ const card = jsx.element(
9
+ 'Card',
10
+ [jsx.attribute('title', jsx.stringValue('Fish & chips'))],
11
+ [jsx.text('Hello')],
12
+ 0,
13
+ true
14
+ )
15
+ jsx.printJSX(card) // <Card title={"Fish & chips"}>Hello</Card>
16
+ ```
17
+
18
+ `jsx.stringValue` and `jsx.text` keep a value as plain JSX only when JSX reads it back unchanged; anything with quotes, entities, braces, angle brackets, backslashes, or line breaks becomes a string literal. `jsx.printModule` prints a whole TSX module, such as an `es` template filled with JSX, quoting every string the same way; dotted tags such as `Switch.Root` print as members of a namespace, and `jsx.spread` passes an object on as attributes.
19
+
20
+ `es` parses TypeScript templates, fills `$name` placeholders, and prints modules:
21
+
22
+ ```ts
23
+ import { es } from '@pairdraw/emit'
24
+
25
+ const module = es.fill(es.parseModule("export const title = '$title'"), {
26
+ $title: es.string('Checkout')
27
+ })
28
+ es.printModule(module) // export const title = 'Checkout';
29
+ ```
30
+
31
+ `vue` builds templates and single-file components. Text and attribute values are escaped as HTML with `entities`, and text also writes `{` as an entity, since Vue reads `{{` as an interpolation before it decodes entities:
32
+
33
+ ```ts
34
+ import { es, vue } from '@pairdraw/emit'
35
+
36
+ const template = vue.element('SwitchRoot', [
37
+ vue.attribute('class', 'switch'),
38
+ vue.model(es.identifier('checked'))
39
+ ])
40
+ vue.printTemplate(template) // <SwitchRoot class="switch" v-model="checked" />
41
+ ```
@@ -0,0 +1,217 @@
1
+ import { __exportAll } from "../rolldown-runtime.js";
2
+ import { tsPlugin } from "@sveltejs/acorn-typescript";
3
+ import { Parser } from "acorn";
4
+ import { print } from "esrap";
5
+ import ts from "esrap/languages/ts";
6
+ //#region src/estree.ts
7
+ var estree_exports = /* @__PURE__ */ __exportAll({
8
+ OMIT: () => OMIT,
9
+ array: () => array,
10
+ call: () => call,
11
+ child: () => child,
12
+ children: () => children,
13
+ fill: () => fill,
14
+ identifier: () => identifier,
15
+ isIdentifierName: () => isIdentifierName,
16
+ isNode: () => isNode,
17
+ json: () => json,
18
+ member: () => member,
19
+ number: () => number,
20
+ object: () => object,
21
+ objectType: () => objectType,
22
+ parseExpression: () => parseExpression,
23
+ parseModule: () => parseModule,
24
+ parseType: () => parseType,
25
+ printExpression: () => printExpression,
26
+ printModule: () => printModule,
27
+ string: () => string,
28
+ stringUnionType: () => stringUnionType
29
+ });
30
+ const TSParser = Parser.extend(tsPlugin());
31
+ /** Whether a value is a syntax node, as opposed to a primitive field of one. */
32
+ function isNode(value) {
33
+ return typeof value === "object" && value !== null && "type" in value;
34
+ }
35
+ /** The node under `key`, or undefined when it is absent or not a node. */
36
+ function child(node, key) {
37
+ const value = node?.[key];
38
+ return isNode(value) ? value : void 0;
39
+ }
40
+ function children(node, key) {
41
+ const value = node?.[key];
42
+ return Array.isArray(value) ? value.filter(isNode) : [];
43
+ }
44
+ function parseModule(source) {
45
+ const program = TSParser.parse(source, {
46
+ ecmaVersion: "latest",
47
+ sourceType: "module"
48
+ });
49
+ if (!isNode(program)) throw new Error("Expected a module");
50
+ return {
51
+ ...program,
52
+ body: children(program, "body")
53
+ };
54
+ }
55
+ function parseExpression(source) {
56
+ const expression = child(parseModule(`(${source})`).body.at(0), "expression");
57
+ if (!expression) throw new Error(`Expected an expression: ${source}`);
58
+ return expression;
59
+ }
60
+ function parseType(source) {
61
+ const type = child(parseModule(`type T = ${source}`).body.at(0), "typeAnnotation");
62
+ if (!type) throw new Error(`Expected a type: ${source}`);
63
+ return type;
64
+ }
65
+ /** A hole value that removes the object property holding it. */
66
+ const OMIT = Symbol("omit");
67
+ /**
68
+ * Replace `$name` placeholders — identifiers, type references, and string literals — with
69
+ * nodes. A property whose value is filled with `OMIT` is removed.
70
+ */
71
+ function fill(template, holes) {
72
+ const hole = (name) => typeof name === "string" ? holes[name] : void 0;
73
+ const holeOf = (node) => {
74
+ if (node.type === "Identifier") return hole(node.name);
75
+ if (node.type === "Literal") return hole(node.value);
76
+ if (node.type === "TSTypeReference") return hole(child(node, "typeName")?.name);
77
+ };
78
+ const omitted = (node) => isNode(node) && node.type === "Property" && hole(child(node, "value")?.name) === OMIT;
79
+ const replacement = (node) => {
80
+ const value = holeOf(node);
81
+ if (!value || value === OMIT) return void 0;
82
+ const annotation = child(node, "typeAnnotation");
83
+ return annotation ? {
84
+ ...structuredClone(value),
85
+ typeAnnotation: visit(annotation)
86
+ } : structuredClone(value);
87
+ };
88
+ function visit(node) {
89
+ const filled = replacement(node);
90
+ if (filled) return filled;
91
+ const copy = { ...node };
92
+ for (const [key, value] of Object.entries(node)) if (Array.isArray(value)) copy[key] = value.filter((item) => !omitted(item)).map((item) => isNode(item) ? visit(item) : item);
93
+ else if (isNode(value)) copy[key] = visit(value);
94
+ return copy;
95
+ }
96
+ return visit(template);
97
+ }
98
+ function printModule(program) {
99
+ return print(program, ts(), { indent: " " }).code;
100
+ }
101
+ /** One expression, as a template binding or another host language embeds it. */
102
+ function printExpression(expression) {
103
+ return printModule({
104
+ type: "Program",
105
+ sourceType: "module",
106
+ body: [{
107
+ type: "ExpressionStatement",
108
+ expression
109
+ }]
110
+ }).trim().replace(/;$/, "");
111
+ }
112
+ const identifier = (name) => ({
113
+ type: "Identifier",
114
+ name
115
+ });
116
+ const string = (value) => ({
117
+ type: "Literal",
118
+ value
119
+ });
120
+ /** A finite number, with a negative one written as `-` before its magnitude, as source does. */
121
+ function number(value) {
122
+ if (!Number.isFinite(value)) throw new Error(`Not a finite number: ${value}`);
123
+ const literal = {
124
+ type: "Literal",
125
+ value: Math.abs(value)
126
+ };
127
+ return value < 0 ? {
128
+ type: "UnaryExpression",
129
+ operator: "-",
130
+ prefix: true,
131
+ argument: literal
132
+ } : literal;
133
+ }
134
+ /** Whether `name` can be written as it is, as a JavaScript identifier, rather than quoted. */
135
+ const isIdentifierName = (name) => /^[A-Za-z_$][\w$]*$/.test(name);
136
+ const propertyKey = (key) => isIdentifierName(key) ? identifier(key) : string(key);
137
+ function object(entries) {
138
+ return {
139
+ type: "ObjectExpression",
140
+ properties: entries.map(([key, value]) => ({
141
+ type: "Property",
142
+ kind: "init",
143
+ key: propertyKey(key),
144
+ value,
145
+ computed: false,
146
+ method: false,
147
+ shorthand: false
148
+ }))
149
+ };
150
+ }
151
+ const array = (elements) => ({
152
+ type: "ArrayExpression",
153
+ elements
154
+ });
155
+ /** `object.key`, or `object['key']` for a key that is not an identifier. */
156
+ function member(object, key) {
157
+ const computed = !/^[A-Za-z_$][\w$]*$/.test(key);
158
+ return {
159
+ type: "MemberExpression",
160
+ object,
161
+ property: computed ? string(key) : identifier(key),
162
+ computed,
163
+ optional: false
164
+ };
165
+ }
166
+ /**
167
+ * A value read from JSON written as source: strings, finite numbers, booleans, null, and lists
168
+ * and objects of them. Anything else, such as a function or an infinite number, is null.
169
+ */
170
+ function json(value) {
171
+ if (typeof value === "string") return string(value);
172
+ if (typeof value === "number") return Number.isFinite(value) ? number(value) : json(null);
173
+ if (typeof value === "boolean" || value === null) return {
174
+ type: "Literal",
175
+ value
176
+ };
177
+ if (Array.isArray(value)) return array(value.map(json));
178
+ if (typeof value === "object") return object(Object.entries(value).map(([key, item]) => [key, json(item)]));
179
+ return json(null);
180
+ }
181
+ /** A call of a function by name, such as a helper inside an exported prop value. */
182
+ const call = (callee, args) => ({
183
+ type: "CallExpression",
184
+ callee: identifier(callee),
185
+ arguments: args,
186
+ optional: false
187
+ });
188
+ function stringUnionType(values) {
189
+ const literals = values.map((value) => ({
190
+ type: "TSLiteralType",
191
+ literal: string(value)
192
+ }));
193
+ return literals.length === 1 && literals[0] ? literals[0] : {
194
+ type: "TSUnionType",
195
+ types: literals
196
+ };
197
+ }
198
+ /** An object type; a member whose third element is `true` is optional. */
199
+ function objectType(entries) {
200
+ return {
201
+ type: "TSTypeLiteral",
202
+ members: entries.map(([key, typeAnnotation, optional = false]) => ({
203
+ type: "TSPropertySignature",
204
+ key: propertyKey(key),
205
+ computed: false,
206
+ optional,
207
+ typeAnnotation: {
208
+ type: "TSTypeAnnotation",
209
+ typeAnnotation
210
+ }
211
+ }))
212
+ };
213
+ }
214
+ //#endregion
215
+ export { estree_exports, isNode, printExpression, printModule };
216
+
217
+ //# sourceMappingURL=estree.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"estree.js","names":[],"sources":["../../src/estree.ts"],"sourcesContent":["import { tsPlugin } from '@sveltejs/acorn-typescript'\nimport { Parser } from 'acorn'\nimport { print } from 'esrap'\nimport ts from 'esrap/languages/ts'\n\n/** An ESTree or TS-ESTree node, as acorn parses it and esrap prints it. */\nexport interface SyntaxNode {\n type: string\n [key: string]: unknown\n}\n\nconst TSParser = Parser.extend(tsPlugin())\n\n/** Whether a value is a syntax node, as opposed to a primitive field of one. */\nexport function isNode(value: unknown): value is SyntaxNode {\n return typeof value === 'object' && value !== null && 'type' in value\n}\n\n/** The node under `key`, or undefined when it is absent or not a node. */\nexport function child(node: SyntaxNode | undefined, key: string): SyntaxNode | undefined {\n const value = node?.[key]\n return isNode(value) ? value : undefined\n}\n\nexport function children(node: SyntaxNode | undefined, key: string): SyntaxNode[] {\n const value = node?.[key]\n return Array.isArray(value) ? value.filter(isNode) : []\n}\n\nexport function parseModule(source: string): SyntaxNode & { body: SyntaxNode[] } {\n const program: unknown = TSParser.parse(source, { ecmaVersion: 'latest', sourceType: 'module' })\n if (!isNode(program)) throw new Error('Expected a module')\n return { ...program, body: children(program, 'body') }\n}\n\nexport function parseExpression(source: string): SyntaxNode {\n const expression = child(parseModule(`(${source})`).body.at(0), 'expression')\n if (!expression) throw new Error(`Expected an expression: ${source}`)\n return expression\n}\n\nexport function parseType(source: string): SyntaxNode {\n const type = child(parseModule(`type T = ${source}`).body.at(0), 'typeAnnotation')\n if (!type) throw new Error(`Expected a type: ${source}`)\n return type\n}\n\n/** A hole value that removes the object property holding it. */\nexport const OMIT = Symbol('omit')\n\n/**\n * Replace `$name` placeholders — identifiers, type references, and string literals — with\n * nodes. A property whose value is filled with `OMIT` is removed.\n */\nexport function fill<T extends SyntaxNode>(\n template: T,\n holes: Record<string, SyntaxNode | typeof OMIT>\n): T {\n const hole = (name: unknown) => (typeof name === 'string' ? holes[name] : undefined)\n const holeOf = (node: SyntaxNode) => {\n if (node.type === 'Identifier') return hole(node.name)\n if (node.type === 'Literal') return hole(node.value)\n if (node.type === 'TSTypeReference') return hole(child(node, 'typeName')?.name)\n return undefined\n }\n const omitted = (node: unknown) =>\n isNode(node) && node.type === 'Property' && hole(child(node, 'value')?.name) === OMIT\n const replacement = (node: SyntaxNode): SyntaxNode | undefined => {\n const value = holeOf(node)\n if (!value || value === OMIT) return undefined\n // `$name: Story` keeps its annotation when the identifier is filled, with its own holes filled.\n const annotation = child(node, 'typeAnnotation')\n return annotation\n ? { ...structuredClone(value), typeAnnotation: visit(annotation) }\n : structuredClone(value)\n }\n function visit(node: SyntaxNode): SyntaxNode {\n const filled = replacement(node)\n if (filled) return filled\n const copy: SyntaxNode = { ...node }\n for (const [key, value] of Object.entries(node)) {\n if (Array.isArray(value))\n copy[key] = value\n .filter((item) => !omitted(item))\n .map((item) => (isNode(item) ? visit(item) : item))\n else if (isNode(value)) copy[key] = visit(value)\n }\n return copy\n }\n return visit(template) as T\n}\n\nexport function printModule(program: SyntaxNode): string {\n return print(program, ts(), { indent: ' ' }).code\n}\n\n/** One expression, as a template binding or another host language embeds it. */\nexport function printExpression(expression: SyntaxNode): string {\n const program = {\n type: 'Program',\n sourceType: 'module',\n body: [{ type: 'ExpressionStatement', expression }]\n }\n return printModule(program).trim().replace(/;$/, '')\n}\n\nexport const identifier = (name: string): SyntaxNode => ({ type: 'Identifier', name })\n\nexport const string = (value: string): SyntaxNode => ({ type: 'Literal', value })\n\n/** A finite number, with a negative one written as `-` before its magnitude, as source does. */\nexport function number(value: number): SyntaxNode {\n if (!Number.isFinite(value)) throw new Error(`Not a finite number: ${value}`)\n const literal = { type: 'Literal', value: Math.abs(value) }\n return value < 0\n ? { type: 'UnaryExpression', operator: '-', prefix: true, argument: literal }\n : literal\n}\n\n/** Whether `name` can be written as it is, as a JavaScript identifier, rather than quoted. */\nexport const isIdentifierName = (name: string): boolean => /^[A-Za-z_$][\\w$]*$/.test(name)\n\nconst propertyKey = (key: string) => (isIdentifierName(key) ? identifier(key) : string(key))\n\nexport function object(entries: (readonly [string, SyntaxNode])[]): SyntaxNode {\n return {\n type: 'ObjectExpression',\n properties: entries.map(([key, value]) => ({\n type: 'Property',\n kind: 'init',\n key: propertyKey(key),\n value,\n computed: false,\n method: false,\n shorthand: false\n }))\n }\n}\n\nexport const array = (elements: SyntaxNode[]): SyntaxNode => ({ type: 'ArrayExpression', elements })\n\n/** `object.key`, or `object['key']` for a key that is not an identifier. */\nexport function member(object: SyntaxNode, key: string): SyntaxNode {\n const computed = !/^[A-Za-z_$][\\w$]*$/.test(key)\n return {\n type: 'MemberExpression',\n object,\n property: computed ? string(key) : identifier(key),\n computed,\n optional: false\n }\n}\n\n/**\n * A value read from JSON written as source: strings, finite numbers, booleans, null, and lists\n * and objects of them. Anything else, such as a function or an infinite number, is null.\n */\nexport function json(value: unknown): SyntaxNode {\n if (typeof value === 'string') return string(value)\n if (typeof value === 'number') return Number.isFinite(value) ? number(value) : json(null)\n if (typeof value === 'boolean' || value === null) return { type: 'Literal', value }\n if (Array.isArray(value)) return array(value.map(json))\n if (typeof value === 'object')\n return object(Object.entries(value).map(([key, item]) => [key, json(item)]))\n return json(null)\n}\n\n/** A call of a function by name, such as a helper inside an exported prop value. */\nexport const call = (callee: string, args: SyntaxNode[]): SyntaxNode => ({\n type: 'CallExpression',\n callee: identifier(callee),\n arguments: args,\n optional: false\n})\n\nexport function stringUnionType(values: string[]): SyntaxNode {\n const literals = values.map((value) => ({ type: 'TSLiteralType', literal: string(value) }))\n return literals.length === 1 && literals[0]\n ? literals[0]\n : { type: 'TSUnionType', types: literals }\n}\n\n/** An object type; a member whose third element is `true` is optional. */\nexport function objectType(entries: [string, SyntaxNode, boolean?][]): SyntaxNode {\n return {\n type: 'TSTypeLiteral',\n members: entries.map(([key, typeAnnotation, optional = false]) => ({\n type: 'TSPropertySignature',\n key: propertyKey(key),\n computed: false,\n optional,\n typeAnnotation: { type: 'TSTypeAnnotation', typeAnnotation }\n }))\n }\n}\n"],"mappings":";;;;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AC;CACtD,IAAI,OAAO,UAAU,UACnB,OAAO,OAAO,OAAO,QAAQ,KAAK,CAAC,CAAC,KAAK,CAAC,KAAK,UAAU,CAAC,KAAK,KAAK,IAAI,CAAC,CAAC,CAAC;CAC7E,OAAO,KAAK,IAAI;AAClB;;AAGA,MAAa,QAAQ,QAAgB,UAAoC;CACvE,MAAM;CACN,QAAQ,WAAW,MAAM;CACzB,WAAW;CACX,UAAU;AACZ;AAEA,SAAgB,gBAAgB,QAA8B;CAC5D,MAAM,WAAW,OAAO,KAAK,WAAW;EAAE,MAAM;EAAiB,SAAS,OAAO,KAAK;CAAE,EAAE;CAC1F,OAAO,SAAS,WAAW,KAAK,SAAS,KACrC,SAAS,KACT;EAAE,MAAM;EAAe,OAAO;CAAS;AAC7C;;AAGA,SAAgB,WAAW,SAAuD;CAChF,OAAO;EACL,MAAM;EACN,SAAS,QAAQ,KAAK,CAAC,KAAK,gBAAgB,WAAW,YAAY;GACjE,MAAM;GACN,KAAK,YAAY,GAAG;GACpB,UAAU;GACV;GACA,gBAAgB;IAAE,MAAM;IAAoB;GAAe;EAC7D,EAAE;CACJ;AACF"}
@@ -0,0 +1,258 @@
1
+ import { __exportAll } from "../rolldown-runtime.js";
2
+ import { isNode, printExpression, printModule as printModule$1 } from "./estree.js";
3
+ import { print } from "esrap";
4
+ import tsx from "esrap/languages/tsx";
5
+ import { escapeAttribute, escapeText } from "entities";
6
+ //#region src/jsx.ts
7
+ var jsx_exports = /* @__PURE__ */ __exportAll({
8
+ attribute: () => attribute$1,
9
+ container: () => container,
10
+ element: () => element$1,
11
+ fragment: () => fragment,
12
+ identifier: () => identifier,
13
+ inlineText: () => inlineText,
14
+ literal: () => literal,
15
+ printJSX: () => printJSX,
16
+ printModule: () => printModule,
17
+ spread: () => spread,
18
+ stringValue: () => stringValue,
19
+ text: () => text$1,
20
+ whitespace: () => whitespace
21
+ });
22
+ /**
23
+ * JSX attribute strings end at `"`, decode `&` entities, and keep backslashes literally,
24
+ * so the printer's escapes for backslashes and line breaks would change the value. JSX
25
+ * text also treats braces and angle brackets as syntax and trims whitespace at line
26
+ * edges. Anything else is written as a string literal, which the printer escapes.
27
+ */
28
+ const LITERAL_ATTRIBUTE = /^[^"&\\\r\n]*$/;
29
+ const LITERAL_TEXT = /^[^{}<>&\r\n]*$/;
30
+ const identifier = (name) => ({
31
+ type: "JSXIdentifier",
32
+ name
33
+ });
34
+ /** A tag name; a dotted one such as `Switch.Root` is a member of a namespace. */
35
+ function tagName(tag) {
36
+ const [first = tag, ...rest] = tag.split(".");
37
+ return rest.reduce((object, property) => ({
38
+ type: "JSXMemberExpression",
39
+ object,
40
+ property: identifier(property)
41
+ }), identifier(first));
42
+ }
43
+ const literal = (value) => ({
44
+ type: "Literal",
45
+ value
46
+ });
47
+ const container = (expression) => ({
48
+ type: "JSXExpressionContainer",
49
+ expression
50
+ });
51
+ /** Raw JSX text, printed as is. */
52
+ const whitespace = (value) => ({
53
+ type: "JSXText",
54
+ value,
55
+ raw: value
56
+ });
57
+ /** A string attribute value: quoted when JSX keeps it as written, an expression otherwise. */
58
+ const stringValue = (value) => LITERAL_ATTRIBUTE.test(value) ? literal(value) : container(literal(value));
59
+ /** `{...expression}`, passing an object's properties on as attributes. */
60
+ const spread = (argument) => ({
61
+ type: "JSXSpreadAttribute",
62
+ argument
63
+ });
64
+ /** An attribute; a null value prints the bare name, as for `true`. */
65
+ const attribute$1 = (name, value) => ({
66
+ type: "JSXAttribute",
67
+ name: identifier(name),
68
+ value
69
+ });
70
+ /** Text content: plain JSX text when it survives as written, a string expression otherwise. */
71
+ function text$1(value) {
72
+ return LITERAL_TEXT.test(value) && value.trim() === value && value.length > 0 ? whitespace(value) : container(literal(value));
73
+ }
74
+ /**
75
+ * Text that shares a line with elements, as beside a span. JSX trims whitespace only at line
76
+ * edges, so text without a line break is kept as written, spaces at its ends included.
77
+ */
78
+ function inlineText(value) {
79
+ return LITERAL_TEXT.test(value) && value.length > 0 ? whitespace(value) : container(literal(value));
80
+ }
81
+ /** Children on their own lines; JSX drops whitespace-only lines between elements. */
82
+ function indented(children, depth) {
83
+ const inner = `\n${" ".repeat(depth + 1)}`;
84
+ return [...children.flatMap((child) => [whitespace(inner), child]), whitespace(`\n${" ".repeat(depth)}`)];
85
+ }
86
+ /**
87
+ * An element at nesting `depth`. Children go on their own lines unless `inline`, as for a
88
+ * lone text child; without children the element self-closes.
89
+ */
90
+ function element$1(tag, attributes, children, depth, inline = false) {
91
+ const name = tagName(tag);
92
+ const content = inline || children.length === 0 ? children : indented(children, depth);
93
+ return {
94
+ type: "JSXElement",
95
+ openingElement: {
96
+ type: "JSXOpeningElement",
97
+ name,
98
+ attributes,
99
+ selfClosing: content.length === 0
100
+ },
101
+ closingElement: content.length > 0 ? {
102
+ type: "JSXClosingElement",
103
+ name
104
+ } : null,
105
+ children: content
106
+ };
107
+ }
108
+ /** `<>…</>`: children without an element around them, laid out as an element's are. */
109
+ function fragment(children, depth) {
110
+ return {
111
+ type: "JSXFragment",
112
+ openingFragment: { type: "JSXOpeningFragment" },
113
+ closingFragment: { type: "JSXClosingFragment" },
114
+ children: children.length === 0 ? [] : indented(children, depth)
115
+ };
116
+ }
117
+ function printJSX(node) {
118
+ return print(node, tsx({ quotes: "double" }), { indent: " " }).code;
119
+ }
120
+ /** A copy without strings' source spelling, so the printer quotes every string the same way. */
121
+ function withoutRawStrings(node) {
122
+ const copy = { ...node };
123
+ if (node.type === "Literal" && typeof node.value === "string") delete copy.raw;
124
+ for (const [key, value] of Object.entries(node)) if (Array.isArray(value)) copy[key] = value.map((item) => isNode(item) ? withoutRawStrings(item) : item);
125
+ else if (isNode(value)) copy[key] = withoutRawStrings(value);
126
+ return copy;
127
+ }
128
+ /**
129
+ * A TSX module, such as a component built with `es` templates and JSX from this module. Strings
130
+ * parsed from a template and strings built here print with the same double quotes.
131
+ */
132
+ function printModule(program) {
133
+ return print(withoutRawStrings(program), tsx({ quotes: "double" }), { indent: " " }).code;
134
+ }
135
+ //#endregion
136
+ //#region src/vue.ts
137
+ var vue_exports = /* @__PURE__ */ __exportAll({
138
+ attribute: () => attribute,
139
+ bound: () => bound,
140
+ componentElements: () => componentElements,
141
+ element: () => element,
142
+ interpolation: () => interpolation,
143
+ model: () => model,
144
+ printComponent: () => printComponent,
145
+ printTemplate: () => printTemplate,
146
+ renderIf: () => renderIf,
147
+ text: () => text
148
+ });
149
+ /**
150
+ * Text and attribute values are escaped as HTML by `entities`. Vue also reads `{{` as an
151
+ * interpolation before it decodes entities, so text writes `{` as one too and a design's text
152
+ * can never become template syntax.
153
+ */
154
+ const templateText = (value) => escapeText(value).replaceAll("{", "&#123;");
155
+ const attribute = (name, value) => ({
156
+ type: "static",
157
+ name,
158
+ value
159
+ });
160
+ const bound = (name, expression) => ({
161
+ type: "bound",
162
+ name,
163
+ expression
164
+ });
165
+ const model = (expression, argument) => ({
166
+ type: "model",
167
+ argument,
168
+ expression
169
+ });
170
+ const renderIf = (expression) => ({
171
+ type: "if",
172
+ expression
173
+ });
174
+ const element = (tag, attributes = [], children = []) => ({
175
+ type: "element",
176
+ tag,
177
+ attributes,
178
+ children
179
+ });
180
+ const text = (value) => ({
181
+ type: "text",
182
+ value
183
+ });
184
+ const interpolation = (expression) => ({
185
+ type: "interpolation",
186
+ expression
187
+ });
188
+ function printAttribute(item) {
189
+ if (item.type === "static") return `${item.name}="${escapeAttribute(item.value)}"`;
190
+ const value = escapeAttribute(printExpression(item.expression));
191
+ if (item.type === "bound") return `:${item.name}="${value}"`;
192
+ if (item.type === "if") return `v-if="${value}"`;
193
+ return `${item.argument ? `v-model:${item.argument}` : "v-model"}="${value}"`;
194
+ }
195
+ /** Markup with nothing added around it, as text content needs. */
196
+ function printInline(node) {
197
+ if (node.type === "text") return templateText(node.value);
198
+ if (node.type === "interpolation") {
199
+ const expression = printExpression(node.expression);
200
+ if (expression.includes("}}")) throw new Error(`An interpolated expression cannot contain "}}": ${expression}`);
201
+ return `{{ ${expression} }}`;
202
+ }
203
+ const open = [node.tag, ...node.attributes.map(printAttribute)].join(" ");
204
+ if (node.children.length === 0) return `<${open} />`;
205
+ return `<${open}>${node.children.map(printInline).join("")}</${node.tag}>`;
206
+ }
207
+ function printNode(node, depth) {
208
+ const indent = " ".repeat(depth);
209
+ if (node.type !== "element" || node.children.some((child) => child.type !== "element")) return `${indent}${printInline(node)}`;
210
+ const open = [node.tag, ...node.attributes.map(printAttribute)].join(" ");
211
+ if (node.children.length === 0) return `${indent}<${open} />`;
212
+ const children = node.children.map((child) => printNode(child, depth + 1));
213
+ return [
214
+ `${indent}<${open}>`,
215
+ ...children,
216
+ `${indent}</${node.tag}>`
217
+ ].join("\n");
218
+ }
219
+ /** A template's markup, one element per line. */
220
+ function printTemplate(root) {
221
+ return printNode(root, 0);
222
+ }
223
+ /**
224
+ * A raw block's content, which ends at the first closing tag for its element. Strings in the
225
+ * script and values in the stylesheet can come from an imported design, so a closing tag in
226
+ * them is written `<\\/`, which JavaScript strings and CSS both read back as `</`.
227
+ */
228
+ const rawBlock = (tag, content) => `<${tag}>\n${content.trim().replace(/<\/(?=script|style)/gi, "<\\/")}\n</${tag.split(" ")[0]}>`;
229
+ /** Whether a component's script has anything to write, so it gets a script block. */
230
+ const hasScript = (script) => printModule$1(script).trim() !== "";
231
+ function templateElements(node) {
232
+ return node.type === "element" ? [node, ...node.children.flatMap(templateElements)] : [];
233
+ }
234
+ /**
235
+ * The elements `printComponent` writes, in the order they open: the template's own, between
236
+ * `null`s for the script, template, and style blocks that hold them.
237
+ */
238
+ function componentElements({ script, template, style }) {
239
+ return [
240
+ ...hasScript(script) ? [null] : [],
241
+ null,
242
+ ...templateElements(template),
243
+ ...style ? [null] : []
244
+ ];
245
+ }
246
+ /** A single-file component: script setup, template, and scoped style. */
247
+ function printComponent({ script, template, style }) {
248
+ const code = printModule$1(script);
249
+ return `${[
250
+ ...code.trim() ? [rawBlock("script setup lang=\"ts\"", code)] : [],
251
+ `<template>\n${printNode(template, 1)}\n</template>`,
252
+ ...style ? [rawBlock("style scoped", style)] : []
253
+ ].join("\n\n")}\n`;
254
+ }
255
+ //#endregion
256
+ export { jsx_exports, vue_exports };
257
+
258
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":["attribute","text","element","printModule"],"sources":["../../src/jsx.ts","../../src/vue.ts"],"sourcesContent":["import { print } from 'esrap'\nimport tsx from 'esrap/languages/tsx'\n\nimport { isNode, type SyntaxNode } from './estree'\n\n/**\n * JSX attribute strings end at `\"`, decode `&` entities, and keep backslashes literally,\n * so the printer's escapes for backslashes and line breaks would change the value. JSX\n * text also treats braces and angle brackets as syntax and trims whitespace at line\n * edges. Anything else is written as a string literal, which the printer escapes.\n */\nconst LITERAL_ATTRIBUTE = /^[^\"&\\\\\\r\\n]*$/\nconst LITERAL_TEXT = /^[^{}<>&\\r\\n]*$/\n\nexport const identifier = (name: string): SyntaxNode => ({ type: 'JSXIdentifier', name })\n\n/** A tag name; a dotted one such as `Switch.Root` is a member of a namespace. */\nfunction tagName(tag: string): SyntaxNode {\n const [first = tag, ...rest] = tag.split('.')\n return rest.reduce<SyntaxNode>(\n (object, property) => ({ type: 'JSXMemberExpression', object, property: identifier(property) }),\n identifier(first)\n )\n}\n\nexport const literal = (value: string | number | boolean): SyntaxNode => ({\n type: 'Literal',\n value\n})\n\nexport const container = (expression: SyntaxNode): SyntaxNode => ({\n type: 'JSXExpressionContainer',\n expression\n})\n\n/** Raw JSX text, printed as is. */\nexport const whitespace = (value: string): SyntaxNode => ({ type: 'JSXText', value, raw: value })\n\n/** A string attribute value: quoted when JSX keeps it as written, an expression otherwise. */\nexport const stringValue = (value: string): SyntaxNode =>\n LITERAL_ATTRIBUTE.test(value) ? literal(value) : container(literal(value))\n\n/** `{...expression}`, passing an object's properties on as attributes. */\nexport const spread = (argument: SyntaxNode): SyntaxNode => ({\n type: 'JSXSpreadAttribute',\n argument\n})\n\n/** An attribute; a null value prints the bare name, as for `true`. */\nexport const attribute = (name: string, value: SyntaxNode | null): SyntaxNode => ({\n type: 'JSXAttribute',\n name: identifier(name),\n value\n})\n\n/** Text content: plain JSX text when it survives as written, a string expression otherwise. */\nexport function text(value: string): SyntaxNode {\n const plain = LITERAL_TEXT.test(value) && value.trim() === value && value.length > 0\n return plain ? whitespace(value) : container(literal(value))\n}\n\n/**\n * Text that shares a line with elements, as beside a span. JSX trims whitespace only at line\n * edges, so text without a line break is kept as written, spaces at its ends included.\n */\nexport function inlineText(value: string): SyntaxNode {\n const plain = LITERAL_TEXT.test(value) && value.length > 0\n return plain ? whitespace(value) : container(literal(value))\n}\n\n/** Children on their own lines; JSX drops whitespace-only lines between elements. */\nfunction indented(children: SyntaxNode[], depth: number): SyntaxNode[] {\n const inner = `\\n${' '.repeat(depth + 1)}`\n return [\n ...children.flatMap((child) => [whitespace(inner), child]),\n whitespace(`\\n${' '.repeat(depth)}`)\n ]\n}\n\n/**\n * An element at nesting `depth`. Children go on their own lines unless `inline`, as for a\n * lone text child; without children the element self-closes.\n */\nexport function element(\n tag: string,\n attributes: SyntaxNode[],\n children: SyntaxNode[],\n depth: number,\n inline = false\n): SyntaxNode {\n const name = tagName(tag)\n const content = inline || children.length === 0 ? children : indented(children, depth)\n return {\n type: 'JSXElement',\n openingElement: {\n type: 'JSXOpeningElement',\n name,\n attributes,\n selfClosing: content.length === 0\n },\n closingElement: content.length > 0 ? { type: 'JSXClosingElement', name } : null,\n children: content\n }\n}\n\n/** `<>…</>`: children without an element around them, laid out as an element's are. */\nexport function fragment(children: SyntaxNode[], depth: number): SyntaxNode {\n return {\n type: 'JSXFragment',\n openingFragment: { type: 'JSXOpeningFragment' },\n closingFragment: { type: 'JSXClosingFragment' },\n children: children.length === 0 ? [] : indented(children, depth)\n }\n}\n\nexport function printJSX(node: SyntaxNode): string {\n return print(node, tsx({ quotes: 'double' }), { indent: ' ' }).code\n}\n\n/** A copy without strings' source spelling, so the printer quotes every string the same way. */\nfunction withoutRawStrings(node: SyntaxNode): SyntaxNode {\n const copy: SyntaxNode = { ...node }\n if (node.type === 'Literal' && typeof node.value === 'string') delete copy.raw\n for (const [key, value] of Object.entries(node)) {\n if (Array.isArray(value))\n copy[key] = value.map((item: unknown) => (isNode(item) ? withoutRawStrings(item) : item))\n else if (isNode(value)) copy[key] = withoutRawStrings(value)\n }\n return copy\n}\n\n/**\n * A TSX module, such as a component built with `es` templates and JSX from this module. Strings\n * parsed from a template and strings built here print with the same double quotes.\n */\nexport function printModule(program: SyntaxNode): string {\n return print(withoutRawStrings(program), tsx({ quotes: 'double' }), { indent: ' ' }).code\n}\n","import { escapeAttribute, escapeText } from 'entities'\n\nimport { printExpression, printModule, type SyntaxNode } from './estree'\n\n/**\n * Text and attribute values are escaped as HTML by `entities`. Vue also reads `{{` as an\n * interpolation before it decodes entities, so text writes `{` as one too and a design's text\n * can never become template syntax.\n */\nconst templateText = (value: string) => escapeText(value).replaceAll('{', '&#123;')\n\nexport type VueAttribute =\n | { type: 'static'; name: string; value: string }\n /** `:name=\"expression\"` */\n | { type: 'bound'; name: string; expression: SyntaxNode }\n /** `v-model=\"expression\"`, or `v-model:argument` */\n | { type: 'model'; argument?: string; expression: SyntaxNode }\n /** `v-if=\"expression\"`: the element renders only while the expression holds. */\n | { type: 'if'; expression: SyntaxNode }\n\nexport interface VueElement {\n type: 'element'\n tag: string\n attributes: VueAttribute[]\n children: VueNode[]\n}\n\nexport interface VueText {\n type: 'text'\n value: string\n}\n\n/** `{{ expression }}`, printed from a syntax tree so it holds only what the tree says. */\nexport interface VueInterpolation {\n type: 'interpolation'\n expression: SyntaxNode\n}\n\nexport type VueNode = VueElement | VueText | VueInterpolation\n\nexport const attribute = (name: string, value: string): VueAttribute => ({\n type: 'static',\n name,\n value\n})\n\nexport const bound = (name: string, expression: SyntaxNode): VueAttribute => ({\n type: 'bound',\n name,\n expression\n})\n\nexport const model = (expression: SyntaxNode, argument?: string): VueAttribute => ({\n type: 'model',\n argument,\n expression\n})\n\nexport const renderIf = (expression: SyntaxNode): VueAttribute => ({ type: 'if', expression })\n\nexport const element = (\n tag: string,\n attributes: VueAttribute[] = [],\n children: VueNode[] = []\n): VueElement => ({ type: 'element', tag, attributes, children })\n\nexport const text = (value: string): VueText => ({ type: 'text', value })\n\nexport const interpolation = (expression: SyntaxNode): VueInterpolation => ({\n type: 'interpolation',\n expression\n})\n\nfunction printAttribute(item: VueAttribute): string {\n if (item.type === 'static') return `${item.name}=\"${escapeAttribute(item.value)}\"`\n const value = escapeAttribute(printExpression(item.expression))\n if (item.type === 'bound') return `:${item.name}=\"${value}\"`\n if (item.type === 'if') return `v-if=\"${value}\"`\n return `${item.argument ? `v-model:${item.argument}` : 'v-model'}=\"${value}\"`\n}\n\n/** Markup with nothing added around it, as text content needs. */\nfunction printInline(node: VueNode): string {\n if (node.type === 'text') return templateText(node.value)\n if (node.type === 'interpolation') {\n const expression = printExpression(node.expression)\n // The template ends an interpolation at the first `}}`, wherever it falls.\n if (expression.includes('}}'))\n throw new Error(`An interpolated expression cannot contain \"}}\": ${expression}`)\n return `{{ ${expression} }}`\n }\n const open = [node.tag, ...node.attributes.map(printAttribute)].join(' ')\n if (node.children.length === 0) return `<${open} />`\n return `<${open}>${node.children.map(printInline).join('')}</${node.tag}>`\n}\n\nfunction printNode(node: VueNode, depth: number): string {\n const indent = ' '.repeat(depth)\n // Vue renders whitespace between text and elements as a space, so an element with text or\n // an interpolation in it keeps its children on its own line, exactly as given.\n if (node.type !== 'element' || node.children.some((child) => child.type !== 'element'))\n return `${indent}${printInline(node)}`\n const open = [node.tag, ...node.attributes.map(printAttribute)].join(' ')\n if (node.children.length === 0) return `${indent}<${open} />`\n const children = node.children.map((child) => printNode(child, depth + 1))\n return [`${indent}<${open}>`, ...children, `${indent}</${node.tag}>`].join('\\n')\n}\n\n/** A template's markup, one element per line. */\nexport function printTemplate(root: VueNode): string {\n return printNode(root, 0)\n}\n\nexport interface VueComponent {\n /** The `<script setup lang=\"ts\">` body, a TypeScript program from `es`. */\n script: SyntaxNode\n template: VueNode\n /** Stylesheet text for a `<style scoped>` block. */\n style?: string\n}\n\n/**\n * A raw block's content, which ends at the first closing tag for its element. Strings in the\n * script and values in the stylesheet can come from an imported design, so a closing tag in\n * them is written `<\\\\/`, which JavaScript strings and CSS both read back as `</`.\n */\nconst rawBlock = (tag: string, content: string) =>\n `<${tag}>\\n${content.trim().replace(/<\\/(?=script|style)/gi, '<\\\\/')}\\n</${tag.split(' ')[0]}>`\n\n/** Whether a component's script has anything to write, so it gets a script block. */\nconst hasScript = (script: SyntaxNode) => printModule(script).trim() !== ''\n\nfunction templateElements(node: VueNode): VueElement[] {\n return node.type === 'element' ? [node, ...node.children.flatMap(templateElements)] : []\n}\n\n/**\n * The elements `printComponent` writes, in the order they open: the template's own, between\n * `null`s for the script, template, and style blocks that hold them.\n */\nexport function componentElements({\n script,\n template,\n style\n}: VueComponent): (VueElement | null)[] {\n return [\n ...(hasScript(script) ? [null] : []),\n null,\n ...templateElements(template),\n ...(style ? [null] : [])\n ]\n}\n\n/** A single-file component: script setup, template, and scoped style. */\nexport function printComponent({ script, template, style }: VueComponent): string {\n const code = printModule(script)\n // A component with nothing to import or declare has no script block.\n const blocks = [\n ...(code.trim() ? [rawBlock('script setup lang=\"ts\"', code)] : []),\n `<template>\\n${printNode(template, 1)}\\n</template>`,\n ...(style ? [rawBlock('style scoped', style)] : [])\n ]\n return `${blocks.join('\\n\\n')}\\n`\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAWA,MAAM,oBAAoB;AAC1B,MAAM,eAAe;AAErB,MAAa,cAAc,UAA8B;CAAE,MAAM;CAAiB;AAAK;;AAGvF,SAAS,QAAQ,KAAyB;CACxC,MAAM,CAAC,QAAQ,KAAK,GAAG,QAAQ,IAAI,MAAM,GAAG;CAC5C,OAAO,KAAK,QACT,QAAQ,cAAc;EAAE,MAAM;EAAuB;EAAQ,UAAU,WAAW,QAAQ;CAAE,IAC7F,WAAW,KAAK,CAClB;AACF;AAEA,MAAa,WAAW,WAAkD;CACxE,MAA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@
1
+ declare namespace estree_d_exports {
2
+ export { OMIT, SyntaxNode, array, call, child, children, fill, identifier$1 as identifier, isIdentifierName, isNode, json, member, number, object, objectType, parseExpression, parseModule, parseType, printExpression, printModule$1 as printModule, string, stringUnionType };
3
+ }
4
+ /** An ESTree or TS-ESTree node, as acorn parses it and esrap prints it. */
5
+ interface SyntaxNode {
6
+ type: string;
7
+ [key: string]: unknown;
8
+ }
9
+ /** Whether a value is a syntax node, as opposed to a primitive field of one. */
10
+ declare function isNode(value: unknown): value is SyntaxNode;
11
+ /** The node under `key`, or undefined when it is absent or not a node. */
12
+ declare function child(node: SyntaxNode | undefined, key: string): SyntaxNode | undefined;
13
+ declare function children(node: SyntaxNode | undefined, key: string): SyntaxNode[];
14
+ declare function parseModule(source: string): SyntaxNode & {
15
+ body: SyntaxNode[];
16
+ };
17
+ declare function parseExpression(source: string): SyntaxNode;
18
+ declare function parseType(source: string): SyntaxNode;
19
+ /** A hole value that removes the object property holding it. */
20
+ declare const OMIT: unique symbol;
21
+ /**
22
+ * Replace `$name` placeholders — identifiers, type references, and string literals — with
23
+ * nodes. A property whose value is filled with `OMIT` is removed.
24
+ */
25
+ declare function fill<T extends SyntaxNode>(template: T, holes: Record<string, SyntaxNode | typeof OMIT>): T;
26
+ declare function printModule$1(program: SyntaxNode): string;
27
+ /** One expression, as a template binding or another host language embeds it. */
28
+ declare function printExpression(expression: SyntaxNode): string;
29
+ declare const identifier$1: (name: string) => SyntaxNode;
30
+ declare const string: (value: string) => SyntaxNode;
31
+ /** A finite number, with a negative one written as `-` before its magnitude, as source does. */
32
+ declare function number(value: number): SyntaxNode;
33
+ /** Whether `name` can be written as it is, as a JavaScript identifier, rather than quoted. */
34
+ declare const isIdentifierName: (name: string) => boolean;
35
+ declare function object(entries: (readonly [string, SyntaxNode])[]): SyntaxNode;
36
+ declare const array: (elements: SyntaxNode[]) => SyntaxNode;
37
+ /** `object.key`, or `object['key']` for a key that is not an identifier. */
38
+ declare function member(object: SyntaxNode, key: string): SyntaxNode;
39
+ /**
40
+ * A value read from JSON written as source: strings, finite numbers, booleans, null, and lists
41
+ * and objects of them. Anything else, such as a function or an infinite number, is null.
42
+ */
43
+ declare function json(value: unknown): SyntaxNode;
44
+ /** A call of a function by name, such as a helper inside an exported prop value. */
45
+ declare const call: (callee: string, args: SyntaxNode[]) => SyntaxNode;
46
+ declare function stringUnionType(values: string[]): SyntaxNode;
47
+ /** An object type; a member whose third element is `true` is optional. */
48
+ declare function objectType(entries: [string, SyntaxNode, boolean?][]): SyntaxNode;
49
+ declare namespace jsx_d_exports {
50
+ export { attribute$1 as attribute, container, element$1 as element, fragment, identifier, inlineText, literal, printJSX, printModule, spread, stringValue, text$1 as text, whitespace };
51
+ }
52
+ declare const identifier: (name: string) => SyntaxNode;
53
+ declare const literal: (value: string | number | boolean) => SyntaxNode;
54
+ declare const container: (expression: SyntaxNode) => SyntaxNode;
55
+ /** Raw JSX text, printed as is. */
56
+ declare const whitespace: (value: string) => SyntaxNode;
57
+ /** A string attribute value: quoted when JSX keeps it as written, an expression otherwise. */
58
+ declare const stringValue: (value: string) => SyntaxNode;
59
+ /** `{...expression}`, passing an object's properties on as attributes. */
60
+ declare const spread: (argument: SyntaxNode) => SyntaxNode;
61
+ /** An attribute; a null value prints the bare name, as for `true`. */
62
+ declare const attribute$1: (name: string, value: SyntaxNode | null) => SyntaxNode;
63
+ /** Text content: plain JSX text when it survives as written, a string expression otherwise. */
64
+ declare function text$1(value: string): SyntaxNode;
65
+ /**
66
+ * Text that shares a line with elements, as beside a span. JSX trims whitespace only at line
67
+ * edges, so text without a line break is kept as written, spaces at its ends included.
68
+ */
69
+ declare function inlineText(value: string): SyntaxNode;
70
+ /**
71
+ * An element at nesting `depth`. Children go on their own lines unless `inline`, as for a
72
+ * lone text child; without children the element self-closes.
73
+ */
74
+ declare function element$1(tag: string, attributes: SyntaxNode[], children: SyntaxNode[], depth: number, inline?: boolean): SyntaxNode;
75
+ /** `<>…</>`: children without an element around them, laid out as an element's are. */
76
+ declare function fragment(children: SyntaxNode[], depth: number): SyntaxNode;
77
+ declare function printJSX(node: SyntaxNode): string;
78
+ /**
79
+ * A TSX module, such as a component built with `es` templates and JSX from this module. Strings
80
+ * parsed from a template and strings built here print with the same double quotes.
81
+ */
82
+ declare function printModule(program: SyntaxNode): string;
83
+ declare namespace vue_d_exports {
84
+ export { VueAttribute, VueComponent, VueElement, VueInterpolation, VueNode, VueText, attribute, bound, componentElements, element, interpolation, model, printComponent, printTemplate, renderIf, text };
85
+ }
86
+ type VueAttribute = {
87
+ type: 'static';
88
+ name: string;
89
+ value: string;
90
+ } |
91
+ /** `:name="expression"` */
92
+ {
93
+ type: 'bound';
94
+ name: string;
95
+ expression: SyntaxNode;
96
+ } |
97
+ /** `v-model="expression"`, or `v-model:argument` */
98
+ {
99
+ type: 'model';
100
+ argument?: string;
101
+ expression: SyntaxNode;
102
+ } |
103
+ /** `v-if="expression"`: the element renders only while the expression holds. */
104
+ {
105
+ type: 'if';
106
+ expression: SyntaxNode;
107
+ };
108
+ interface VueElement {
109
+ type: 'element';
110
+ tag: string;
111
+ attributes: VueAttribute[];
112
+ children: VueNode[];
113
+ }
114
+ interface VueText {
115
+ type: 'text';
116
+ value: string;
117
+ }
118
+ /** `{{ expression }}`, printed from a syntax tree so it holds only what the tree says. */
119
+ interface VueInterpolation {
120
+ type: 'interpolation';
121
+ expression: SyntaxNode;
122
+ }
123
+ type VueNode = VueElement | VueText | VueInterpolation;
124
+ declare const attribute: (name: string, value: string) => VueAttribute;
125
+ declare const bound: (name: string, expression: SyntaxNode) => VueAttribute;
126
+ declare const model: (expression: SyntaxNode, argument?: string) => VueAttribute;
127
+ declare const renderIf: (expression: SyntaxNode) => VueAttribute;
128
+ declare const element: (tag: string, attributes?: VueAttribute[], children?: VueNode[]) => VueElement;
129
+ declare const text: (value: string) => VueText;
130
+ declare const interpolation: (expression: SyntaxNode) => VueInterpolation;
131
+ /** A template's markup, one element per line. */
132
+ declare function printTemplate(root: VueNode): string;
133
+ interface VueComponent {
134
+ /** The `<script setup lang="ts">` body, a TypeScript program from `es`. */
135
+ script: SyntaxNode;
136
+ template: VueNode;
137
+ /** Stylesheet text for a `<style scoped>` block. */
138
+ style?: string;
139
+ }
140
+ /**
141
+ * The elements `printComponent` writes, in the order they open: the template's own, between
142
+ * `null`s for the script, template, and style blocks that hold them.
143
+ */
144
+ declare function componentElements({ script, template, style }: VueComponent): (VueElement | null)[];
145
+ /** A single-file component: script setup, template, and scoped style. */
146
+ declare function printComponent({ script, template, style }: VueComponent): string;
147
+ //#endregion
148
+ export { type SyntaxNode, estree_d_exports as es, jsx_d_exports as jsx, vue_d_exports as vue };
149
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../src/estree.ts","../src/jsx.ts","../src/vue.ts"],"mappings":";;;;UAMiB;EACf;GACC;;;iBAMa,OAAO,iBAAiB,SAAS;;iBAKjC,MAAM,MAAM,wBAAwB,cAAc;iBAKlD,SAAS,MAAM,wBAAwB,cAAc;iBAKrD,YAAY,iBAAiB;EAAe,MAAM;;iBAMlD,gBAAgB,iBAAiB;iBAMjC,UAAU,iBAAiB;;cAO9B;;;;;iBAMG,KAAK,UAAU,YAC7B,UAAU,GACV,OAAO,eAAe,oBAAoB,QACzC;iBAmCa,cAAY,SAAS;;iBAKrB,gBAAgB,YAAY;cAS/B,eAAc,iBAAe;cAE7B,SAAU,kBAAgB;;iBAGvB,OAAO,gBAAgB;;cAS1B,mBAAoB;iBAIjB,OAAO,4BAA4B,iBAAiB;cAevD,QAAS,UAAU,iBAAe;;iBAG/B,OAAO,QAAQ,YAAY,cAAc;;;;;iBAezC,KAAK,iBAAiB;;cAWzB,OAAQ,gBAAgB,MAAM,iBAAe;iBAO1C,gBAAgB,mBAAmB;;iBAQnC,WAAW,kBAAkB,0BAA0B;;;;cCzK1D,aAAc,iBAAe;cAW7B,UAAW,qCAAmC;cAK9C,YAAa,YAAY,eAAa;;cAMtC,aAAc,kBAAgB;;cAG9B,cAAe,kBAAgB;;cAI/B,SAAU,UAAU,eAAa;;cAMjC,cAAa,cAAc,OAAO,sBAAoB;;iBAOnD,OAAK,gBAAgB;;;;;iBASrB,WAAW,gBAAgB;;;;;iBAkB3B,UACd,aACA,YAAY,cACZ,UAAU,cACV,eACA,mBACC;;iBAiBa,SAAS,UAAU,cAAc,gBAAgB;iBASjD,SAAS,MAAM;;;;;iBAoBf,YAAY,SAAS;;;;KC5HzB;EACN;EAAgB;EAAc;;;;EAE9B;EAAe;EAAc,YAAY;;;;EAEzC;EAAe;EAAmB,YAAY;;;;EAE9C;EAAY,YAAY;;UAEb;EACf;EACA;EACA,YAAY;EACZ,UAAU;;UAGK;EACf;EACA;;;UAIe;EACf;EACA,YAAY;;KAGF,UAAU,aAAa,UAAU;cAEhC,YAAa,cAAc,kBAAgB;cAM3C,QAAS,cAAc,YAAY,eAAa;cAMhD,QAAS,YAAY,YAAY,sBAAoB;cAMrD,WAAY,YAAY,eAAa;cAErC,UACX,aACA,aAAY,gBACZ,WAAU,cACT;cAEU,OAAQ,kBAAgB;cAExB,gBAAiB,YAAY,eAAa;;iBAyCvC,cAAc,MAAM;UAInB;;EAEf,QAAQ;EACR,UAAU;;EAEV;;;;;;iBAsBc,oBACd,QACA,UACA,SACC,gBAAgB;;iBAUH,iBAAiB,QAAQ,UAAU,SAAS"}
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ import { estree_exports } from "./chunks/estree.js";
2
+ import { jsx_exports, vue_exports } from "./chunks/index.js";
3
+ export { estree_exports as es, jsx_exports as jsx, vue_exports as vue };
@@ -0,0 +1,13 @@
1
+ //#region \0rolldown/runtime.js
2
+ var __defProp = Object.defineProperty;
3
+ var __exportAll = (all, no_symbols) => {
4
+ let target = {};
5
+ for (var name in all) __defProp(target, name, {
6
+ get: all[name],
7
+ enumerable: true
8
+ });
9
+ if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
10
+ return target;
11
+ };
12
+ //#endregion
13
+ export { __exportAll };
package/package.json CHANGED
@@ -1,6 +1,39 @@
1
1
  {
2
2
  "name": "@pairdraw/emit",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.16.0",
4
+ "license": "MIT",
5
+ "files": [
6
+ "dist",
7
+ "src",
8
+ "README.md"
9
+ ],
10
+ "main": "./dist/index.js",
11
+ "types": "./dist/index.d.ts",
12
+ "dependencies": {
13
+ "@sveltejs/acorn-typescript": "^1.0.13",
14
+ "acorn": "^8.18.0",
15
+ "entities": "^8.0.0",
16
+ "esrap": "^2.3.11"
17
+ },
18
+ "exports": {
19
+ ".": {
20
+ "types": "./dist/index.d.ts",
21
+ "import": "./dist/index.js",
22
+ "default": "./dist/index.js"
23
+ }
24
+ },
25
+ "imports": {
26
+ "#emit/*": {
27
+ "types": "./src/*.ts",
28
+ "default": "./dist/*.js"
29
+ }
30
+ },
31
+ "description": "How Pairdraw exporters emit source: JavaScript, TypeScript, and JSX built as ESTree and printed with esrap.",
32
+ "repository": {
33
+ "type": "git",
34
+ "url": "git+https://github.com/BadryansahBangsawan/pairdraw.git",
35
+ "directory": "packages/emit"
36
+ },
37
+ "type": "module",
38
+ "sideEffects": false
39
+ }
package/src/estree.ts ADDED
@@ -0,0 +1,195 @@
1
+ import { tsPlugin } from '@sveltejs/acorn-typescript'
2
+ import { Parser } from 'acorn'
3
+ import { print } from 'esrap'
4
+ import ts from 'esrap/languages/ts'
5
+
6
+ /** An ESTree or TS-ESTree node, as acorn parses it and esrap prints it. */
7
+ export interface SyntaxNode {
8
+ type: string
9
+ [key: string]: unknown
10
+ }
11
+
12
+ const TSParser = Parser.extend(tsPlugin())
13
+
14
+ /** Whether a value is a syntax node, as opposed to a primitive field of one. */
15
+ export function isNode(value: unknown): value is SyntaxNode {
16
+ return typeof value === 'object' && value !== null && 'type' in value
17
+ }
18
+
19
+ /** The node under `key`, or undefined when it is absent or not a node. */
20
+ export function child(node: SyntaxNode | undefined, key: string): SyntaxNode | undefined {
21
+ const value = node?.[key]
22
+ return isNode(value) ? value : undefined
23
+ }
24
+
25
+ export function children(node: SyntaxNode | undefined, key: string): SyntaxNode[] {
26
+ const value = node?.[key]
27
+ return Array.isArray(value) ? value.filter(isNode) : []
28
+ }
29
+
30
+ export function parseModule(source: string): SyntaxNode & { body: SyntaxNode[] } {
31
+ const program: unknown = TSParser.parse(source, { ecmaVersion: 'latest', sourceType: 'module' })
32
+ if (!isNode(program)) throw new Error('Expected a module')
33
+ return { ...program, body: children(program, 'body') }
34
+ }
35
+
36
+ export function parseExpression(source: string): SyntaxNode {
37
+ const expression = child(parseModule(`(${source})`).body.at(0), 'expression')
38
+ if (!expression) throw new Error(`Expected an expression: ${source}`)
39
+ return expression
40
+ }
41
+
42
+ export function parseType(source: string): SyntaxNode {
43
+ const type = child(parseModule(`type T = ${source}`).body.at(0), 'typeAnnotation')
44
+ if (!type) throw new Error(`Expected a type: ${source}`)
45
+ return type
46
+ }
47
+
48
+ /** A hole value that removes the object property holding it. */
49
+ export const OMIT = Symbol('omit')
50
+
51
+ /**
52
+ * Replace `$name` placeholders — identifiers, type references, and string literals — with
53
+ * nodes. A property whose value is filled with `OMIT` is removed.
54
+ */
55
+ export function fill<T extends SyntaxNode>(
56
+ template: T,
57
+ holes: Record<string, SyntaxNode | typeof OMIT>
58
+ ): T {
59
+ const hole = (name: unknown) => (typeof name === 'string' ? holes[name] : undefined)
60
+ const holeOf = (node: SyntaxNode) => {
61
+ if (node.type === 'Identifier') return hole(node.name)
62
+ if (node.type === 'Literal') return hole(node.value)
63
+ if (node.type === 'TSTypeReference') return hole(child(node, 'typeName')?.name)
64
+ return undefined
65
+ }
66
+ const omitted = (node: unknown) =>
67
+ isNode(node) && node.type === 'Property' && hole(child(node, 'value')?.name) === OMIT
68
+ const replacement = (node: SyntaxNode): SyntaxNode | undefined => {
69
+ const value = holeOf(node)
70
+ if (!value || value === OMIT) return undefined
71
+ // `$name: Story` keeps its annotation when the identifier is filled, with its own holes filled.
72
+ const annotation = child(node, 'typeAnnotation')
73
+ return annotation
74
+ ? { ...structuredClone(value), typeAnnotation: visit(annotation) }
75
+ : structuredClone(value)
76
+ }
77
+ function visit(node: SyntaxNode): SyntaxNode {
78
+ const filled = replacement(node)
79
+ if (filled) return filled
80
+ const copy: SyntaxNode = { ...node }
81
+ for (const [key, value] of Object.entries(node)) {
82
+ if (Array.isArray(value))
83
+ copy[key] = value
84
+ .filter((item) => !omitted(item))
85
+ .map((item) => (isNode(item) ? visit(item) : item))
86
+ else if (isNode(value)) copy[key] = visit(value)
87
+ }
88
+ return copy
89
+ }
90
+ return visit(template) as T
91
+ }
92
+
93
+ export function printModule(program: SyntaxNode): string {
94
+ return print(program, ts(), { indent: ' ' }).code
95
+ }
96
+
97
+ /** One expression, as a template binding or another host language embeds it. */
98
+ export function printExpression(expression: SyntaxNode): string {
99
+ const program = {
100
+ type: 'Program',
101
+ sourceType: 'module',
102
+ body: [{ type: 'ExpressionStatement', expression }]
103
+ }
104
+ return printModule(program).trim().replace(/;$/, '')
105
+ }
106
+
107
+ export const identifier = (name: string): SyntaxNode => ({ type: 'Identifier', name })
108
+
109
+ export const string = (value: string): SyntaxNode => ({ type: 'Literal', value })
110
+
111
+ /** A finite number, with a negative one written as `-` before its magnitude, as source does. */
112
+ export function number(value: number): SyntaxNode {
113
+ if (!Number.isFinite(value)) throw new Error(`Not a finite number: ${value}`)
114
+ const literal = { type: 'Literal', value: Math.abs(value) }
115
+ return value < 0
116
+ ? { type: 'UnaryExpression', operator: '-', prefix: true, argument: literal }
117
+ : literal
118
+ }
119
+
120
+ /** Whether `name` can be written as it is, as a JavaScript identifier, rather than quoted. */
121
+ export const isIdentifierName = (name: string): boolean => /^[A-Za-z_$][\w$]*$/.test(name)
122
+
123
+ const propertyKey = (key: string) => (isIdentifierName(key) ? identifier(key) : string(key))
124
+
125
+ export function object(entries: (readonly [string, SyntaxNode])[]): SyntaxNode {
126
+ return {
127
+ type: 'ObjectExpression',
128
+ properties: entries.map(([key, value]) => ({
129
+ type: 'Property',
130
+ kind: 'init',
131
+ key: propertyKey(key),
132
+ value,
133
+ computed: false,
134
+ method: false,
135
+ shorthand: false
136
+ }))
137
+ }
138
+ }
139
+
140
+ export const array = (elements: SyntaxNode[]): SyntaxNode => ({ type: 'ArrayExpression', elements })
141
+
142
+ /** `object.key`, or `object['key']` for a key that is not an identifier. */
143
+ export function member(object: SyntaxNode, key: string): SyntaxNode {
144
+ const computed = !/^[A-Za-z_$][\w$]*$/.test(key)
145
+ return {
146
+ type: 'MemberExpression',
147
+ object,
148
+ property: computed ? string(key) : identifier(key),
149
+ computed,
150
+ optional: false
151
+ }
152
+ }
153
+
154
+ /**
155
+ * A value read from JSON written as source: strings, finite numbers, booleans, null, and lists
156
+ * and objects of them. Anything else, such as a function or an infinite number, is null.
157
+ */
158
+ export function json(value: unknown): SyntaxNode {
159
+ if (typeof value === 'string') return string(value)
160
+ if (typeof value === 'number') return Number.isFinite(value) ? number(value) : json(null)
161
+ if (typeof value === 'boolean' || value === null) return { type: 'Literal', value }
162
+ if (Array.isArray(value)) return array(value.map(json))
163
+ if (typeof value === 'object')
164
+ return object(Object.entries(value).map(([key, item]) => [key, json(item)]))
165
+ return json(null)
166
+ }
167
+
168
+ /** A call of a function by name, such as a helper inside an exported prop value. */
169
+ export const call = (callee: string, args: SyntaxNode[]): SyntaxNode => ({
170
+ type: 'CallExpression',
171
+ callee: identifier(callee),
172
+ arguments: args,
173
+ optional: false
174
+ })
175
+
176
+ export function stringUnionType(values: string[]): SyntaxNode {
177
+ const literals = values.map((value) => ({ type: 'TSLiteralType', literal: string(value) }))
178
+ return literals.length === 1 && literals[0]
179
+ ? literals[0]
180
+ : { type: 'TSUnionType', types: literals }
181
+ }
182
+
183
+ /** An object type; a member whose third element is `true` is optional. */
184
+ export function objectType(entries: [string, SyntaxNode, boolean?][]): SyntaxNode {
185
+ return {
186
+ type: 'TSTypeLiteral',
187
+ members: entries.map(([key, typeAnnotation, optional = false]) => ({
188
+ type: 'TSPropertySignature',
189
+ key: propertyKey(key),
190
+ computed: false,
191
+ optional,
192
+ typeAnnotation: { type: 'TSTypeAnnotation', typeAnnotation }
193
+ }))
194
+ }
195
+ }
package/src/index.ts ADDED
@@ -0,0 +1,4 @@
1
+ export * as es from './estree'
2
+ export * as jsx from './jsx'
3
+ export * as vue from './vue'
4
+ export type { SyntaxNode } from './estree'
package/src/jsx.ts ADDED
@@ -0,0 +1,138 @@
1
+ import { print } from 'esrap'
2
+ import tsx from 'esrap/languages/tsx'
3
+
4
+ import { isNode, type SyntaxNode } from './estree'
5
+
6
+ /**
7
+ * JSX attribute strings end at `"`, decode `&` entities, and keep backslashes literally,
8
+ * so the printer's escapes for backslashes and line breaks would change the value. JSX
9
+ * text also treats braces and angle brackets as syntax and trims whitespace at line
10
+ * edges. Anything else is written as a string literal, which the printer escapes.
11
+ */
12
+ const LITERAL_ATTRIBUTE = /^[^"&\\\r\n]*$/
13
+ const LITERAL_TEXT = /^[^{}<>&\r\n]*$/
14
+
15
+ export const identifier = (name: string): SyntaxNode => ({ type: 'JSXIdentifier', name })
16
+
17
+ /** A tag name; a dotted one such as `Switch.Root` is a member of a namespace. */
18
+ function tagName(tag: string): SyntaxNode {
19
+ const [first = tag, ...rest] = tag.split('.')
20
+ return rest.reduce<SyntaxNode>(
21
+ (object, property) => ({ type: 'JSXMemberExpression', object, property: identifier(property) }),
22
+ identifier(first)
23
+ )
24
+ }
25
+
26
+ export const literal = (value: string | number | boolean): SyntaxNode => ({
27
+ type: 'Literal',
28
+ value
29
+ })
30
+
31
+ export const container = (expression: SyntaxNode): SyntaxNode => ({
32
+ type: 'JSXExpressionContainer',
33
+ expression
34
+ })
35
+
36
+ /** Raw JSX text, printed as is. */
37
+ export const whitespace = (value: string): SyntaxNode => ({ type: 'JSXText', value, raw: value })
38
+
39
+ /** A string attribute value: quoted when JSX keeps it as written, an expression otherwise. */
40
+ export const stringValue = (value: string): SyntaxNode =>
41
+ LITERAL_ATTRIBUTE.test(value) ? literal(value) : container(literal(value))
42
+
43
+ /** `{...expression}`, passing an object's properties on as attributes. */
44
+ export const spread = (argument: SyntaxNode): SyntaxNode => ({
45
+ type: 'JSXSpreadAttribute',
46
+ argument
47
+ })
48
+
49
+ /** An attribute; a null value prints the bare name, as for `true`. */
50
+ export const attribute = (name: string, value: SyntaxNode | null): SyntaxNode => ({
51
+ type: 'JSXAttribute',
52
+ name: identifier(name),
53
+ value
54
+ })
55
+
56
+ /** Text content: plain JSX text when it survives as written, a string expression otherwise. */
57
+ export function text(value: string): SyntaxNode {
58
+ const plain = LITERAL_TEXT.test(value) && value.trim() === value && value.length > 0
59
+ return plain ? whitespace(value) : container(literal(value))
60
+ }
61
+
62
+ /**
63
+ * Text that shares a line with elements, as beside a span. JSX trims whitespace only at line
64
+ * edges, so text without a line break is kept as written, spaces at its ends included.
65
+ */
66
+ export function inlineText(value: string): SyntaxNode {
67
+ const plain = LITERAL_TEXT.test(value) && value.length > 0
68
+ return plain ? whitespace(value) : container(literal(value))
69
+ }
70
+
71
+ /** Children on their own lines; JSX drops whitespace-only lines between elements. */
72
+ function indented(children: SyntaxNode[], depth: number): SyntaxNode[] {
73
+ const inner = `\n${' '.repeat(depth + 1)}`
74
+ return [
75
+ ...children.flatMap((child) => [whitespace(inner), child]),
76
+ whitespace(`\n${' '.repeat(depth)}`)
77
+ ]
78
+ }
79
+
80
+ /**
81
+ * An element at nesting `depth`. Children go on their own lines unless `inline`, as for a
82
+ * lone text child; without children the element self-closes.
83
+ */
84
+ export function element(
85
+ tag: string,
86
+ attributes: SyntaxNode[],
87
+ children: SyntaxNode[],
88
+ depth: number,
89
+ inline = false
90
+ ): SyntaxNode {
91
+ const name = tagName(tag)
92
+ const content = inline || children.length === 0 ? children : indented(children, depth)
93
+ return {
94
+ type: 'JSXElement',
95
+ openingElement: {
96
+ type: 'JSXOpeningElement',
97
+ name,
98
+ attributes,
99
+ selfClosing: content.length === 0
100
+ },
101
+ closingElement: content.length > 0 ? { type: 'JSXClosingElement', name } : null,
102
+ children: content
103
+ }
104
+ }
105
+
106
+ /** `<>…</>`: children without an element around them, laid out as an element's are. */
107
+ export function fragment(children: SyntaxNode[], depth: number): SyntaxNode {
108
+ return {
109
+ type: 'JSXFragment',
110
+ openingFragment: { type: 'JSXOpeningFragment' },
111
+ closingFragment: { type: 'JSXClosingFragment' },
112
+ children: children.length === 0 ? [] : indented(children, depth)
113
+ }
114
+ }
115
+
116
+ export function printJSX(node: SyntaxNode): string {
117
+ return print(node, tsx({ quotes: 'double' }), { indent: ' ' }).code
118
+ }
119
+
120
+ /** A copy without strings' source spelling, so the printer quotes every string the same way. */
121
+ function withoutRawStrings(node: SyntaxNode): SyntaxNode {
122
+ const copy: SyntaxNode = { ...node }
123
+ if (node.type === 'Literal' && typeof node.value === 'string') delete copy.raw
124
+ for (const [key, value] of Object.entries(node)) {
125
+ if (Array.isArray(value))
126
+ copy[key] = value.map((item: unknown) => (isNode(item) ? withoutRawStrings(item) : item))
127
+ else if (isNode(value)) copy[key] = withoutRawStrings(value)
128
+ }
129
+ return copy
130
+ }
131
+
132
+ /**
133
+ * A TSX module, such as a component built with `es` templates and JSX from this module. Strings
134
+ * parsed from a template and strings built here print with the same double quotes.
135
+ */
136
+ export function printModule(program: SyntaxNode): string {
137
+ return print(withoutRawStrings(program), tsx({ quotes: 'double' }), { indent: ' ' }).code
138
+ }
package/src/vue.ts ADDED
@@ -0,0 +1,164 @@
1
+ import { escapeAttribute, escapeText } from 'entities'
2
+
3
+ import { printExpression, printModule, type SyntaxNode } from './estree'
4
+
5
+ /**
6
+ * Text and attribute values are escaped as HTML by `entities`. Vue also reads `{{` as an
7
+ * interpolation before it decodes entities, so text writes `{` as one too and a design's text
8
+ * can never become template syntax.
9
+ */
10
+ const templateText = (value: string) => escapeText(value).replaceAll('{', '&#123;')
11
+
12
+ export type VueAttribute =
13
+ | { type: 'static'; name: string; value: string }
14
+ /** `:name="expression"` */
15
+ | { type: 'bound'; name: string; expression: SyntaxNode }
16
+ /** `v-model="expression"`, or `v-model:argument` */
17
+ | { type: 'model'; argument?: string; expression: SyntaxNode }
18
+ /** `v-if="expression"`: the element renders only while the expression holds. */
19
+ | { type: 'if'; expression: SyntaxNode }
20
+
21
+ export interface VueElement {
22
+ type: 'element'
23
+ tag: string
24
+ attributes: VueAttribute[]
25
+ children: VueNode[]
26
+ }
27
+
28
+ export interface VueText {
29
+ type: 'text'
30
+ value: string
31
+ }
32
+
33
+ /** `{{ expression }}`, printed from a syntax tree so it holds only what the tree says. */
34
+ export interface VueInterpolation {
35
+ type: 'interpolation'
36
+ expression: SyntaxNode
37
+ }
38
+
39
+ export type VueNode = VueElement | VueText | VueInterpolation
40
+
41
+ export const attribute = (name: string, value: string): VueAttribute => ({
42
+ type: 'static',
43
+ name,
44
+ value
45
+ })
46
+
47
+ export const bound = (name: string, expression: SyntaxNode): VueAttribute => ({
48
+ type: 'bound',
49
+ name,
50
+ expression
51
+ })
52
+
53
+ export const model = (expression: SyntaxNode, argument?: string): VueAttribute => ({
54
+ type: 'model',
55
+ argument,
56
+ expression
57
+ })
58
+
59
+ export const renderIf = (expression: SyntaxNode): VueAttribute => ({ type: 'if', expression })
60
+
61
+ export const element = (
62
+ tag: string,
63
+ attributes: VueAttribute[] = [],
64
+ children: VueNode[] = []
65
+ ): VueElement => ({ type: 'element', tag, attributes, children })
66
+
67
+ export const text = (value: string): VueText => ({ type: 'text', value })
68
+
69
+ export const interpolation = (expression: SyntaxNode): VueInterpolation => ({
70
+ type: 'interpolation',
71
+ expression
72
+ })
73
+
74
+ function printAttribute(item: VueAttribute): string {
75
+ if (item.type === 'static') return `${item.name}="${escapeAttribute(item.value)}"`
76
+ const value = escapeAttribute(printExpression(item.expression))
77
+ if (item.type === 'bound') return `:${item.name}="${value}"`
78
+ if (item.type === 'if') return `v-if="${value}"`
79
+ return `${item.argument ? `v-model:${item.argument}` : 'v-model'}="${value}"`
80
+ }
81
+
82
+ /** Markup with nothing added around it, as text content needs. */
83
+ function printInline(node: VueNode): string {
84
+ if (node.type === 'text') return templateText(node.value)
85
+ if (node.type === 'interpolation') {
86
+ const expression = printExpression(node.expression)
87
+ // The template ends an interpolation at the first `}}`, wherever it falls.
88
+ if (expression.includes('}}'))
89
+ throw new Error(`An interpolated expression cannot contain "}}": ${expression}`)
90
+ return `{{ ${expression} }}`
91
+ }
92
+ const open = [node.tag, ...node.attributes.map(printAttribute)].join(' ')
93
+ if (node.children.length === 0) return `<${open} />`
94
+ return `<${open}>${node.children.map(printInline).join('')}</${node.tag}>`
95
+ }
96
+
97
+ function printNode(node: VueNode, depth: number): string {
98
+ const indent = ' '.repeat(depth)
99
+ // Vue renders whitespace between text and elements as a space, so an element with text or
100
+ // an interpolation in it keeps its children on its own line, exactly as given.
101
+ if (node.type !== 'element' || node.children.some((child) => child.type !== 'element'))
102
+ return `${indent}${printInline(node)}`
103
+ const open = [node.tag, ...node.attributes.map(printAttribute)].join(' ')
104
+ if (node.children.length === 0) return `${indent}<${open} />`
105
+ const children = node.children.map((child) => printNode(child, depth + 1))
106
+ return [`${indent}<${open}>`, ...children, `${indent}</${node.tag}>`].join('\n')
107
+ }
108
+
109
+ /** A template's markup, one element per line. */
110
+ export function printTemplate(root: VueNode): string {
111
+ return printNode(root, 0)
112
+ }
113
+
114
+ export interface VueComponent {
115
+ /** The `<script setup lang="ts">` body, a TypeScript program from `es`. */
116
+ script: SyntaxNode
117
+ template: VueNode
118
+ /** Stylesheet text for a `<style scoped>` block. */
119
+ style?: string
120
+ }
121
+
122
+ /**
123
+ * A raw block's content, which ends at the first closing tag for its element. Strings in the
124
+ * script and values in the stylesheet can come from an imported design, so a closing tag in
125
+ * them is written `<\\/`, which JavaScript strings and CSS both read back as `</`.
126
+ */
127
+ const rawBlock = (tag: string, content: string) =>
128
+ `<${tag}>\n${content.trim().replace(/<\/(?=script|style)/gi, '<\\/')}\n</${tag.split(' ')[0]}>`
129
+
130
+ /** Whether a component's script has anything to write, so it gets a script block. */
131
+ const hasScript = (script: SyntaxNode) => printModule(script).trim() !== ''
132
+
133
+ function templateElements(node: VueNode): VueElement[] {
134
+ return node.type === 'element' ? [node, ...node.children.flatMap(templateElements)] : []
135
+ }
136
+
137
+ /**
138
+ * The elements `printComponent` writes, in the order they open: the template's own, between
139
+ * `null`s for the script, template, and style blocks that hold them.
140
+ */
141
+ export function componentElements({
142
+ script,
143
+ template,
144
+ style
145
+ }: VueComponent): (VueElement | null)[] {
146
+ return [
147
+ ...(hasScript(script) ? [null] : []),
148
+ null,
149
+ ...templateElements(template),
150
+ ...(style ? [null] : [])
151
+ ]
152
+ }
153
+
154
+ /** A single-file component: script setup, template, and scoped style. */
155
+ export function printComponent({ script, template, style }: VueComponent): string {
156
+ const code = printModule(script)
157
+ // A component with nothing to import or declare has no script block.
158
+ const blocks = [
159
+ ...(code.trim() ? [rawBlock('script setup lang="ts"', code)] : []),
160
+ `<template>\n${printNode(template, 1)}\n</template>`,
161
+ ...(style ? [rawBlock('style scoped', style)] : [])
162
+ ]
163
+ return `${blocks.join('\n\n')}\n`
164
+ }