|
| 1 | +import type { Plugin } from "rollup"; |
| 2 | +import type { ESTree } from "rolldown/utils"; |
| 3 | +import { RESOLVED_RE as RAW_RE } from "./raw.ts"; |
| 4 | + |
| 5 | +// Bundlers parse the syntax but do not implement the semantics, so imports with a |
| 6 | +// `bytes` or `text` type attribute are rewritten to the internal prefixes of the raw plugin. |
| 7 | +// https://github.com/tc39/proposal-import-bytes |
| 8 | +// https://github.com/tc39/proposal-import-text |
| 9 | + |
| 10 | +const TYPES = ["bytes", "text"] as const; |
| 11 | +type ImportType = (typeof TYPES)[number]; |
| 12 | + |
| 13 | +const ATTR_RE = /["']?type["']?\s*:\s*["'](bytes|text)["']/; |
| 14 | +const JS_ID_RE = /\.[cm]?[jt]sx?(\?.*)?$/; |
| 15 | + |
| 16 | +// A module specifier with a `bytes` or `text` type attribute |
| 17 | +type TypedImport = { |
| 18 | + source: ESTree.StringLiteral; |
| 19 | + type: ImportType; |
| 20 | + // End of the syntax trailing the specifier (options argument or attributes clause) |
| 21 | + end: number; |
| 22 | +}; |
| 23 | + |
| 24 | +type Comment = { start: number; end: number }; |
| 25 | + |
| 26 | +export async function importAttributes(): Promise<Plugin> { |
| 27 | + const { RolldownMagicString } = await import("rolldown"); |
| 28 | + const { parseSync } = await import("rolldown/utils"); |
| 29 | + |
| 30 | + return { |
| 31 | + name: "nitro:import-attributes", |
| 32 | + transform: { |
| 33 | + order: "pre", |
| 34 | + filter: { |
| 35 | + // Raw modules are file contents rather than source code. Their ids end with a `.js` |
| 36 | + // suffix, so without excluding them, files imported as text would be rewritten too. |
| 37 | + id: { include: JS_ID_RE, exclude: RAW_RE }, |
| 38 | + code: ATTR_RE, |
| 39 | + }, |
| 40 | + handler(code, id) { |
| 41 | + if (!JS_ID_RE.test(id) || RAW_RE.test(id) || !ATTR_RE.test(code)) { |
| 42 | + return; // In case the builder does not support filters |
| 43 | + } |
| 44 | + const filename = id.split("?")[0]!; |
| 45 | + const { program, comments, errors } = parseSync(filename, code); |
| 46 | + if (errors.length > 0) { |
| 47 | + this.warn( |
| 48 | + `Could not parse \`${filename}\` to transform \`bytes\` and \`text\` import attributes: ${errors[0]!.message}` |
| 49 | + ); |
| 50 | + return; |
| 51 | + } |
| 52 | + |
| 53 | + const imports = findTypedImports(program, code, comments); |
| 54 | + if (imports.length === 0) { |
| 55 | + return; |
| 56 | + } |
| 57 | + |
| 58 | + const s = new RolldownMagicString(code); |
| 59 | + for (const { source, type, end } of imports) { |
| 60 | + s.update(source.start, source.end, JSON.stringify(`${type}:${source.value}`)); |
| 61 | + s.remove(source.end, end); |
| 62 | + } |
| 63 | + |
| 64 | + return { |
| 65 | + code: s.toString(), |
| 66 | + // `generateMap` returns a napi class whose fields are prototype getters, so spreading |
| 67 | + // or serializing it yields `{}`. Both builders accept a JSON source map string. |
| 68 | + map: s.generateMap({ hires: true, source: filename }).toString(), |
| 69 | + }; |
| 70 | + }, |
| 71 | + }, |
| 72 | + }; |
| 73 | +} |
| 74 | + |
| 75 | +function findTypedImports( |
| 76 | + program: ESTree.Program, |
| 77 | + code: string, |
| 78 | + comments: Comment[] |
| 79 | +): TypedImport[] { |
| 80 | + const imports: TypedImport[] = []; |
| 81 | + walk(program, (node) => { |
| 82 | + switch (node.type) { |
| 83 | + // import("./file", { with: { type: "bytes" } }) |
| 84 | + case "ImportExpression": { |
| 85 | + const options = node.options; |
| 86 | + if (!isStringLiteral(node.source) || options?.type !== "ObjectExpression") { |
| 87 | + return; |
| 88 | + } |
| 89 | + const type = optionsType(options); |
| 90 | + if (type) { |
| 91 | + imports.push({ source: node.source, type, end: options.end }); |
| 92 | + } |
| 93 | + return; |
| 94 | + } |
| 95 | + // import x from "./file" with { type: "bytes" } (also `export ... from`) |
| 96 | + case "ImportDeclaration": |
| 97 | + case "ExportNamedDeclaration": |
| 98 | + case "ExportAllDeclaration": { |
| 99 | + const lastAttr = node.attributes.at(-1); |
| 100 | + const type = attributesType(node.attributes); |
| 101 | + if (!node.source || !lastAttr || !type) { |
| 102 | + return; |
| 103 | + } |
| 104 | + const end = clauseEnd(code, lastAttr.end, comments); |
| 105 | + if (end !== undefined) { |
| 106 | + imports.push({ source: node.source, type, end }); |
| 107 | + } |
| 108 | + } |
| 109 | + } |
| 110 | + }); |
| 111 | + return imports; |
| 112 | +} |
| 113 | + |
| 114 | +// The `with { ... }` clause has no node of its own: its closing brace is the first |
| 115 | +// `}` following the last attribute that is not part of a comment. |
| 116 | +function clauseEnd(code: string, from: number, comments: Comment[]): number | undefined { |
| 117 | + for (let i = code.indexOf("}", from); i !== -1; i = code.indexOf("}", i + 1)) { |
| 118 | + if (!comments.some((comment) => i >= comment.start && i < comment.end)) { |
| 119 | + return i + 1; |
| 120 | + } |
| 121 | + } |
| 122 | +} |
| 123 | + |
| 124 | +function attributesType(attributes: ESTree.ImportAttribute[]): ImportType | undefined { |
| 125 | + for (const attr of attributes) { |
| 126 | + const key = attr.key.type === "Identifier" ? attr.key.name : attr.key.value; |
| 127 | + if (key === "type" && isImportType(attr.value.value)) { |
| 128 | + return attr.value.value; |
| 129 | + } |
| 130 | + } |
| 131 | +} |
| 132 | + |
| 133 | +function optionsType(options: ESTree.ObjectExpression): ImportType | undefined { |
| 134 | + const withOption = findProperty(options, "with"); |
| 135 | + if (withOption?.type !== "ObjectExpression") { |
| 136 | + return; |
| 137 | + } |
| 138 | + const type = findProperty(withOption, "type"); |
| 139 | + if (type && isStringLiteral(type) && isImportType(type.value)) { |
| 140 | + return type.value; |
| 141 | + } |
| 142 | +} |
| 143 | + |
| 144 | +function findProperty(node: ESTree.ObjectExpression, name: string): ESTree.Expression | undefined { |
| 145 | + for (const prop of node.properties) { |
| 146 | + if (prop.type !== "Property" || prop.computed) { |
| 147 | + continue; |
| 148 | + } |
| 149 | + const key = |
| 150 | + prop.key.type === "Identifier" |
| 151 | + ? prop.key.name |
| 152 | + : isStringLiteral(prop.key) |
| 153 | + ? prop.key.value |
| 154 | + : undefined; |
| 155 | + if (key === name) { |
| 156 | + return prop.value; |
| 157 | + } |
| 158 | + } |
| 159 | +} |
| 160 | + |
| 161 | +function isStringLiteral(node: ESTree.Node): node is ESTree.StringLiteral { |
| 162 | + return node.type === "Literal" && typeof (node as ESTree.StringLiteral).value === "string"; |
| 163 | +} |
| 164 | + |
| 165 | +function isImportType(value: string): value is ImportType { |
| 166 | + return TYPES.includes(value as ImportType); |
| 167 | +} |
| 168 | + |
| 169 | +function walk(node: unknown, visit: (node: ESTree.Node) => void): void { |
| 170 | + if (Array.isArray(node)) { |
| 171 | + for (const child of node) { |
| 172 | + walk(child, visit); |
| 173 | + } |
| 174 | + return; |
| 175 | + } |
| 176 | + if (!node || typeof node !== "object") { |
| 177 | + return; |
| 178 | + } |
| 179 | + const record = node as Record<string, unknown>; |
| 180 | + if (typeof record.type === "string") { |
| 181 | + visit(node as ESTree.Node); |
| 182 | + } |
| 183 | + for (const key in record) { |
| 184 | + if (key !== "parent") { |
| 185 | + walk(record[key], visit); |
| 186 | + } |
| 187 | + } |
| 188 | +} |
0 commit comments