Class: Condenser::DartSassTransformer
- Inherits:
-
NodeProcessor
- Object
- NodeProcessor
- Condenser::DartSassTransformer
- Defined in:
- lib/condenser/transformers/dart_sass_transformer.rb
Direct Known Subclasses
Constant Summary collapse
- ACCEPT =
['text/css', 'text/scss', 'text/sass']
- @@helper_methods =
Set.new
Instance Attribute Summary collapse
-
#options ⇒ Object
Returns the value of attribute options.
Attributes inherited from NodeProcessor
Class Method Summary collapse
-
.add_helper_methods(module_to_add = nil, &block) ⇒ Object
Use this function to append Modules that contain functions to expose to dart-sass.
- .syntax ⇒ Object
Instance Method Summary collapse
- #call(environment, input) ⇒ Object
- #exec_runtime(script) ⇒ Object
- #expand_path(path, base = nil) ⇒ Object
- #find(importee, importer = nil) ⇒ Object
- #helper_method_signatures ⇒ Object
-
#initialize(dir, options = {}) ⇒ DartSassTransformer
constructor
A new instance of DartSassTransformer.
- #resolve(importee, importer = nil) ⇒ Object
Methods inherited from NodeProcessor
#binary, call, #exec_runtime_error, #exec_syntax_error, #name, #npm_install, #npm_module_path, setup
Constructor Details
#initialize(dir, options = {}) ⇒ DartSassTransformer
Returns a new instance of DartSassTransformer.
28 29 30 31 32 33 34 35 |
# File 'lib/condenser/transformers/dart_sass_transformer.rb', line 28 def initialize(dir, = {}) super(dir) npm_install('sass') = .merge({ indentedSyntax: self.class.syntax == :sass }).freeze end |
Instance Attribute Details
#options ⇒ Object
Returns the value of attribute options.
9 10 11 |
# File 'lib/condenser/transformers/dart_sass_transformer.rb', line 9 def end |
Class Method Details
.add_helper_methods(module_to_add = nil, &block) ⇒ Object
Use this function to append Modules that contain functions to expose to dart-sass
13 14 15 16 17 18 19 20 |
# File 'lib/condenser/transformers/dart_sass_transformer.rb', line 13 def self.add_helper_methods(module_to_add = nil, &block) old_methods = self.instance_methods self.include(module_to_add) if module_to_add self.class_eval(&block) if block_given? @@helper_methods.merge(self.instance_methods - old_methods) end |
.syntax ⇒ Object
24 25 26 |
# File 'lib/condenser/transformers/dart_sass_transformer.rb', line 24 def self.syntax :sass end |
Instance Method Details
#call(environment, input) ⇒ Object
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 |
# File 'lib/condenser/transformers/dart_sass_transformer.rb', line 59 def call(environment, input) @context = environment.new_context_class#.new(environment) = { verbose: true, file: File.join('/', input[:filename]) }.merge() @environment = environment @input = input result = exec_runtime(" const fs = require('fs');\n const sass = require(\"\#{npm_module_path('sass')}\");\n const stdin = process.stdin;\n stdin.resume();\n stdin.setEncoding('utf8');\n \n // SET STDOUT to sync so that we don't get in an infinte looping waiting\n // for Ruby to response when we haven't even sent the entire request.\n if (process.stdout._handle) process.stdout._handle.setBlocking(true)\n \n const source = \#{JSON.generate(input[:source])};\n const options = \#{JSON.generate(options)};\n\n var rid = 0;\n function request(method, ...args) {\n var trid = rid;\n rid += 1;\n console.log(JSON.stringify({ rid: trid, method: method, args: args }) + \"\\\\n\");\n \n\n var readBuffer = '';\n var response = null;\n let chunk = new Buffer(1024);\n let bytesRead;\n \n while (response === null) {\n try {\n bytesRead = fs.readSync(stdin.fd, chunk, 0, 1024);\n if (bytesRead === null) { exit(1); }\n readBuffer += chunk.toString('utf8', 0, bytesRead);\n [readBuffer, response] = readResponse(readBuffer);\n } catch (e) {\n if (e.code !== 'EAGAIN') { throw e; }\n }\n }\n return response['return'];\n }\n \n function readResponse(buffer) {\n try {\n var message = JSON.parse(buffer);\n return ['', message];\n } catch(e) {\n if (e.name === \"SyntaxError\") {\n if (e.message.startsWith('Unexpected non-whitespace character after JSON at position ')) {\n let pos = parseInt(e.message.slice(59));\n let [b, r] = readResponse(buffer.slice(0,pos));\n return [b + buffer.slice(pos), r];\n } else if (e.message.startsWith('Unexpected token { in JSON at position ')) {\n // This can be removed, once dropping support for node <= v18\n var pos = parseInt(e.message.slice(39));\n let [b, r] = readResponse(buffer.slice(0,pos));\n return [b + buffer.slice(pos), r];\n } else {\n return [buffer, null];\n }\n } else {\n console.log(JSON.stringify({method: 'error', args: [e.name, e.message]}) + \"\\\\n\");\n process.exit(1);\n }\n }\n }\n \n \n options.importer = function(url, prev) { return request('load', url, prev); };\n \n const call_fn = function(name, types, args) {\n const transformedArgs = [];\n request('log', '==================')\n args.forEach((a, i) => {\n if (types[i] === 'Map') {\n // Don't know how to go from SassMap to hash yet\n transformedArgs.push({});\n } else if (types[i] === 'List') {\n // Don't know how to go from SassList to hash yet\n transformedArgs.push([]);\n } else if (!(a instanceof sass.types[types[i]])) {\n throw \"$url: Expected a string.\"; \n } else {\n transformedArgs.push(a.getValue());\n }\n \n\n // if (types[i] === 'List') { a = a.contents(); }\n });\n request('log', name, transformedArgs, types)\n return new sass.types.String(request('call', name, transformedArgs));\n }\n options.functions = {};\n \#{JSON.generate(helper_method_signatures)}.forEach( (f) => {\n let name = f[0].replace(/-/g, '_').replace(/(^[^\\\\(]+)\\\\(.*\\\\)$/, '$1');\n options.functions[f[0]] = (...a) => call_fn(name, f[1], a);\n })\n \n try {\n options.data = source;\n const result = sass.renderSync(options);\n request('result', result.css.toString());\n process.exit(0);\n } catch(e) {\n request('error', e.name, e.message);\n process.exit(1);\n }\n JS\n \n input[:source] = result\n # input[:map] = map.to_json({})\n input[:linked_assets] += @context.links\n input[:process_dependencies] += @context.dependencies\nend\n") |
#exec_runtime(script) ⇒ Object
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 |
# File 'lib/condenser/transformers/dart_sass_transformer.rb', line 199 def exec_runtime(script) io = IO.popen([binary, '-e', script], 'r+') buffer = String.new result = nil begin while IO.select([io]) && io_read = io.read_nonblock(1_024) buffer << io_read = buffer.split("\n\n") buffer = buffer.end_with?("\n\n") ? String.new : .pop .each do || = JSON.parse() ret = case ['method'] when 'result' result = ['args'][0] nil when 'load' importee = ['args'][0] importer = ['args'][1] if importee.end_with?('*') @context.depend_on(importee) code = String.new resolve(importee, importer).each do |f, i| code << "@import '#{f.filename}';\n" end { contents: code, map: nil } else if asset = find(importee) @context.depend_on(asset.filename) { contents: asset.source, map: asset.sourcemap } else @context.depend_on(importee) nil end end when 'error' io.write(JSON.generate({rid: ['rid'], return: nil})) case ['args'][0] when 'AssetNotFound' = "Could not find import \"#{message['args'][1]}\" for \"#{message['args'][2]}\".\n\n" << build_tree(['args'][3], input, ['args'][2]) raise exec_runtime_error() else raise exec_runtime_error(['args'][0] + ': ' + ['args'][1]) end when 'call' if respond_to?(['args'][0]) send(['args'][0], *['args'][1]) else puts '!!!' end end io.write(JSON.generate({rid: ['rid'], return: ret})) end end rescue Errno::EPIPE, EOFError end io.close if $?.success? result else raise exec_runtime_error(buffer) end end |
#expand_path(path, base = nil) ⇒ Object
191 192 193 194 195 196 197 |
# File 'lib/condenser/transformers/dart_sass_transformer.rb', line 191 def (path, base=nil) if path.start_with?('.') File.(path, File.dirname(base)).delete_prefix(File.('.') + '/') else File.(path).delete_prefix(File.('.') + '/') end end |
#find(importee, importer = nil) ⇒ Object
181 182 183 184 |
# File 'lib/condenser/transformers/dart_sass_transformer.rb', line 181 def find(importee, importer = nil) # importer ||= @input[:source_file] @environment.find((importee, importer), nil, accept: ACCEPT) end |
#helper_method_signatures ⇒ Object
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
# File 'lib/condenser/transformers/dart_sass_transformer.rb', line 37 def helper_method_signatures x = @@helper_methods.map do |name| arity = self.method(name).arity signature = [] types = [] if respond_to?(:"#{name}_signature") send(:"#{name}_signature").each do |arg, type| signature << arg types << type end elsif arity >= 0 arity.times.with_index do |a| signature << "$arg#{a}" types << 'String' end end ["#{name}(#{signature.join(', ')})", types] end x end |
#resolve(importee, importer = nil) ⇒ Object
186 187 188 189 |
# File 'lib/condenser/transformers/dart_sass_transformer.rb', line 186 def resolve(importee, importer = nil) # importer ||= @input[:source_file] @environment.resolve((importee, importer), accept: ACCEPT) end |