• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

DanielXMoore / Civet / 17902339232

22 Sep 2025 02:00AM UTC coverage: 91.615% (+0.008%) from 91.607%
17902339232

push

github

web-flow
Merge pull request #1792 from DanielXMoore/bom

Support Unicode BOM: UTF-8, UTF-16 LE and BE

3678 of 4002 branches covered (91.9%)

Branch coverage included in aggregate %.

24 of 29 new or added lines in 6 files covered. (82.76%)

18884 of 20625 relevant lines covered (91.56%)

16480.67 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

12.54
/source/unplugin/unplugin.civet
1
import { type TransformResult, createUnplugin } from 'unplugin'
1✔
2
import civet, { decode, lib, SourceMap, type CompileOptions, type ParseOptions } from '@danielx/civet'
1✔
3
import { findInDir, loadConfig } from '@danielx/civet/config'
1✔
4
import {
1✔
5
  remapRange,
1✔
6
  flattenDiagnosticMessageText,
1✔
7
  // @ts-ignore
1✔
8
  // using ts-ignore because the version of @danielx/civet typescript is checking against
1✔
9
  // is the one published to npm, not the one in the repo
1✔
10
} from '@danielx/civet/ts-diagnostic'
1✔
11
import * as fs from 'fs'
1✔
12
import path from 'path'
1✔
13
import type { FormatDiagnosticsHost, Diagnostic, System } from 'typescript'
1✔
14
import * as tsvfs from '@typescript/vfs'
1✔
15
import type { UserConfig } from 'vite'
1✔
16
import type { BuildOptions } from 'esbuild'
1✔
17
import os from 'os'
1✔
18
import { DEFAULT_EXTENSIONS } from './constants.mjs'
1✔
19

1✔
20
// Copied from typescript to avoid importing the whole package
1✔
21
enum DiagnosticCategory
1✔
22
  Warning = 0
1✔
23
  Error = 1
1✔
24
  Suggestion = 2
1✔
25
  Message = 3
1✔
26

1✔
27
export type PluginOptions
1✔
28
  implicitExtension?: boolean
1✔
29
  outputExtension?: string
1✔
30
  transformOutput?: (
1✔
31
    code: string
1✔
32
    id: string
1✔
33
  ) => TransformResult | Promise<TransformResult>
1✔
34
  emitDeclaration?: boolean
1✔
35
  declarationExtension?: string
1✔
36
  typecheck?: boolean | string
1✔
37
  ts?: 'civet' | 'esbuild' | 'tsc' | 'preserve'
1✔
38
  /** @deprecated Use "ts" option instead */
1✔
39
  js?: boolean
1✔
40
  /** @deprecated Use "emitDeclaration" instead */
1✔
41
  dts?: boolean
1✔
42
  /** Number of parallel threads to compile with (Node only) */
1✔
43
  threads?: number
1✔
44
  /** Cache compilation results based on file mtime (useful for serve or watch mode) */
1✔
45
  cache?: boolean
1✔
46
  /** config filename, or false/null to not look for default config file */
1✔
47
  config?: string | false | null
1✔
48
  parseOptions?: ParseOptions
1✔
49

1✔
50
type CacheEntry
1✔
51
  mtime: number
1✔
52
  result?: TransformResult
1✔
53
  promise?: Promise<void>
1✔
54

1✔
55
postfixRE := /[?#].*$/s
1✔
56
isWindows := os.platform() is 'win32'
1✔
57
windowsSlashRE := /\\/g
1✔
58
civetSuffix := '.civet'
1✔
59

1✔
60
/**
1✔
61
Extract a possible Civet filename from an id, after removing a possible
1✔
62
outputExtension and/or a query/hash (?/#) postfix.
1✔
63
Returns {filename, postfix} in case you need to add the postfix back.
1✔
64
You should check whether the filename ends in .civet extension,
1✔
65
or needs an implicit .civet extension, or isn't Civet-related at all.
1✔
66
*/
1✔
67
function extractCivetFilename(id: string, outputExtension: string): {filename: string, postfix: string}
×
68
  postfix .= ''
×
69
  filename .= id.replace postfixRE, (match) =>
×
70
    postfix = match
×
71
    ''
×
72
  // Normally the outputExtension (.jsx/.tsx by default) should be present,
×
73
  // but sometimes (e.g. esbuild's alias feature) load directly without resolve
×
74
  if filename.endsWith outputExtension
×
75
    filename = filename[< -outputExtension#]
×
76
  {filename, postfix}
×
77

1✔
78
function tryStatSync(file: string): fs.Stats?
×
79
  try
×
80
    // The "throwIfNoEntry" is a performance optimization for cases where the file does not exist
×
81
    return fs.statSync(file, { throwIfNoEntry: false });
×
82

1✔
83
export function slash(p: string): string
1✔
84
  p.replace windowsSlashRE, '/'
×
85

1✔
86
function normalizePath(id: string): string
×
87
  path.posix.normalize isWindows ? slash(id) : id
×
88

1✔
89
function tryFsResolve(file: string): string?
×
90
  fileStat := tryStatSync file
×
91
  if fileStat?.isFile()
×
92
    normalizePath file
×
93

1✔
94
function resolveAbsolutePath(rootDir: string, id: string, implicitExtension: boolean)
×
95
  file := path.join rootDir, id
×
96
  // Check for existence of resolved file and unresolved id,
×
97
  // without and with implicit .civet extension, and return first existing
×
98
  (or)
×
99
    tryFsResolve(file)
×
100
    implicitExtension and implicitCivet file
×
101
    tryFsResolve id
×
102
    implicitExtension and implicitCivet id
×
103

1✔
104
function implicitCivet(file: string): string?
×
105
  return if tryFsResolve file
×
106
  civet := file + '.civet'
×
107
  return civet if tryFsResolve civet
×
108

1✔
109
export const rawPlugin: Parameters<typeof createUnplugin<PluginOptions>>[0] =
1✔
110
(options: PluginOptions = {}, meta) =>
×
111
  if (options.dts) options.emitDeclaration = options.dts
×
112
  compileOptions: CompileOptions .= {}
×
113

×
114
  ts .= options.ts
×
115
  if (options.js) ts = 'civet'
×
116
  unless ts?
×
117
    console.log 'WARNING: You are using the default mode for `options.ts` which is `"civet"`. This mode does not support all TS features. If this is intentional, you should explicitly set `options.ts` to `"civet"`, or choose a different mode.'
×
118
    ts = "civet"
×
119
  unless ts is in ["civet", "esbuild", "tsc", "preserve"]
×
120
    console.log `WARNING: Invalid option ts: ${JSON.stringify ts}; switching to "civet"`
×
121
    ts = "civet"
×
122

×
123
  transformTS := options.emitDeclaration or options.typecheck
×
124
  outExt :=
×
125
    options.outputExtension ?? (ts is "preserve" ? ".tsx" : ".jsx")
×
126
  implicitExtension := options.implicitExtension ?? true
×
127
  let aliasResolver: (id: string) => string
×
128

×
129
  fsMap: Map<string, string> .= new Map
×
130
  sourceMaps := new Map<string, SourceMap>
×
131
  let compilerOptions: any, compilerOptionsWithSourceMap: any
×
132
  rootDir .= process.cwd()
×
133
  let esbuildOptions: BuildOptions
×
134
  let configErrors: Diagnostic[]?
×
135
  let configFileNames: string[]
×
136

×
137
  tsPromise := if transformTS or ts is "tsc"
×
138
    import('typescript').then .default
×
139
  getFormatHost := (sys: System): FormatDiagnosticsHost =>
×
140
    return {
×
141
      getCurrentDirectory: => sys.getCurrentDirectory()
×
142
      getNewLine: => sys.newLine
×
143
      getCanonicalFileName: sys.useCaseSensitiveFileNames
×
144
        ? (f) => f
×
145
        : (f) => f.toLowerCase()
×
146
    }
×
147

×
148
  cache := new Map<string, CacheEntry> unless options.cache is false
×
149

×
150
  plugin: ReturnType<typeof rawPlugin> := {
×
151
    name: 'unplugin-civet'
×
152
    enforce: 'pre'
×
153

×
154
    async buildStart(): Promise<void>
×
155
      civetConfigPath .= options.config
×
156
      if civetConfigPath is undefined
×
157
        civetConfigPath = await findInDir process.cwd()
×
158
      if civetConfigPath
×
159
        compileOptions = await loadConfig civetConfigPath
×
160
      // Merge parseOptions, with plugin options taking priority
×
161
      compileOptions.parseOptions = {
×
162
        ...compileOptions.parseOptions
×
163
        ...options.parseOptions
×
164
      }
×
165
      compileOptions.threads = options.threads if options.threads?
×
166

×
167
      if transformTS or ts is "tsc"
×
168
        ts := await tsPromise!
×
169

×
170
        tsConfigPath := ts.findConfigFile process.cwd(), ts.sys.fileExists
×
171

×
172
        unless tsConfigPath
×
173
          throw new Error "Could not find 'tsconfig.json'"
×
174

×
175
        { config, error } := ts.readConfigFile
×
176
          tsConfigPath
×
177
          ts.sys.readFile
×
178

×
179
        if error
×
180
          console.error ts.formatDiagnostic error, getFormatHost ts.sys
×
181
          throw error
×
182

×
183
        // Mogrify tsconfig.json "files" field to use .civet.tsx
×
184
        function mogrify(key: string)
×
185
          if key in config and Array.isArray config[key]
×
186
            config[key] = config[key].map (item: unknown) =>
×
187
              return item unless item <? "string"
×
188
              return item.replace(/\.civet\b(?!\.)/g, '.civet.tsx')
×
189
        mogrify "files"
×
190

×
191
        // Override readDirectory (used for include/exclude matching)
×
192
        // to include .civet files, as .civet.tsx files
×
193
        system := {...ts.sys}
×
194
        {readDirectory: systemReadDirectory} := system
×
195
        system.readDirectory = (path: string, extensions?: readonly string[], excludes?: readonly string[], includes?: readonly string[], depth?: number): string[] =>
×
196
          extensions = [ ...(extensions ?? []), ".civet" ]
×
197
          systemReadDirectory(path, extensions, excludes, includes, depth)
×
198
          .map &.endsWith(".civet") ? & + ".tsx" : &
×
199

×
200
        configContents := ts.parseJsonConfigFileContent
×
201
          config
×
202
          system
×
203
          process.cwd()
×
204
        configErrors = configContents.errors
×
205
        configFileNames = configContents.fileNames
×
206

×
207
        compilerOptions = {
×
208
          ...configContents.options
×
209
          target: ts.ScriptTarget.ESNext
×
210
          composite: false
×
211
        }
×
212
        // We use .tsx extensions when type checking, so need to enable
×
213
        // JSX mode even if the user doesn't request/use it.
×
214
        compilerOptions.jsx ??= ts.JsxEmit.Preserve
×
215
        compilerOptionsWithSourceMap = {
×
216
          ...compilerOptions
×
217
          sourceMap: true
×
218
        }
×
219
        fsMap = new Map()
×
220

×
221
    async buildEnd(useConfigFileNames = false): Promise<void>
×
222
      if transformTS
×
223
        const ts = await tsPromise!
×
224

×
225
        // Create a virtual file system with all source files processed so far,
×
226
        // but which further resolves any Civet dependencies that are needed
×
227
        // just for typechecking (e.g. `import type` which get removed in JS).
×
228
        system := tsvfs.createFSBackedSystem fsMap, process.cwd(), ts
×
229
        {
×
230
          fileExists: systemFileExists
×
231
          readFile: systemReadFile
×
232
          readDirectory: systemReadDirectory
×
233
        } := system
×
234

×
235
        system.fileExists = (filename: string): boolean =>
×
236
          if (!filename.endsWith('.civet.tsx')) return systemFileExists(filename)
×
237
          if (fsMap.has(filename)) return true
×
238
          return systemFileExists filename[...-4]
×
239

×
240
        system.readDirectory = (path: string): string[] =>
×
241
          systemReadDirectory(path)
×
242
          .map &.endsWith('.civet') ? & + '.tsx' : &
×
243

×
244
        tsCompileOptions := {
×
245
          ...compileOptions
×
246
          rewriteCivetImports: false
×
247
          rewriteTsImports: true
×
248
        }
×
NEW
249
        system.readFile = (filename: string, encoding: BufferEncoding = 'utf-8'): string? =>
×
250
          // Mogrify package.json imports field to use .civet.tsx
×
251
          if path.basename(filename) is "package.json"
×
252
            json := systemReadFile filename, encoding
×
253
            return json unless json
×
254
            parsed: Record<string, unknown> := JSON.parse(json)
×
255
            modified .= false
×
256
            function recurse(node: unknown): void
×
257
              if node? <? "object"
×
258
                for key in node
×
259
                  value := (node as Record<string, unknown>)[key]
×
260
                  if value <? "string"
×
261
                    if value.endsWith ".civet"
×
262
                      (node as Record<string, unknown>)[key] = value + '.tsx'
×
263
                      modified = true
×
264
                  else if value
×
265
                    recurse value
×
266
            recurse parsed.imports
×
267
            return modified ? JSON.stringify(parsed) : json
×
268

×
269
          // Generate .civet.tsx files on the fly
×
270
          if (!filename.endsWith('.civet.tsx')) return systemReadFile(filename, encoding)
×
271
          if (fsMap.has(filename)) return fsMap.get(filename)
×
272
          civetFilename := filename[...-4]
×
NEW
273
          rawCivetSource := fs.readFileSync civetFilename, {encoding}
×
274
          { code: compiledTS, sourceMap } := civet.compile rawCivetSource, {
×
275
            ...tsCompileOptions
×
276
            filename
×
277
            js: false
×
278
            sourceMap: true
×
279
            sync: true // TS readFile API seems to need to be synchronous
×
280
          }
×
281
          fsMap.set filename, compiledTS
×
282
          sourceMaps.set filename, sourceMap
×
283
          return compiledTS
×
284

×
285
        host := tsvfs.createVirtualCompilerHost
×
286
          system
×
287
          compilerOptions
×
288
          ts
×
289

×
290
        program := ts.createProgram
×
291
          rootNames: useConfigFileNames ? configFileNames : [...fsMap.keys()]
×
292
          options: compilerOptions
×
293
          host: host.compilerHost
×
294

×
295
        diagnostics: Diagnostic[] := ts
×
296
          .getPreEmitDiagnostics(program)
×
297
          .map (diagnostic) =>
×
298
            file := diagnostic.file
×
299
            if (!file) return diagnostic
×
300

×
301
            sourceMap := sourceMaps.get file.fileName
×
302
            if (!sourceMap) return diagnostic
×
303

×
304
            sourcemapLines := sourceMap.lines ?? sourceMap.data.lines
×
305
            range := remapRange(
×
306
              {
×
307
                start: diagnostic.start || 0,
×
308
                end: (diagnostic.start || 0) + (diagnostic.length || 1),
×
309
              },
×
310
              sourcemapLines
×
311
            )
×
312

×
313
            {
×
314
              ...diagnostic,
×
315
              messageText: flattenDiagnosticMessageText(diagnostic.messageText),
×
316
              length: diagnostic.length,
×
317
              start: range.start,
×
318
            }
×
319

×
320
        if configErrors?#
×
321
          diagnostics.unshift ...configErrors
×
322

×
323
        if diagnostics# > 0
×
324
          console.error
×
325
            ts.formatDiagnosticsWithColorAndContext
×
326
              diagnostics
×
327
              getFormatHost ts.sys
×
328
          if options.typecheck
×
329
            failures: DiagnosticCategory[] .= []
×
330
            if options.typecheck <? "string"
×
331
              if (options.typecheck.includes('error')) failures.push(DiagnosticCategory.Error)
×
332
              if (options.typecheck.includes('warning')) failures.push(DiagnosticCategory.Warning)
×
333
              if (options.typecheck.includes('suggestion')) failures.push(DiagnosticCategory.Suggestion)
×
334
              if (options.typecheck.includes('message')) failures.push(DiagnosticCategory.Message)
×
335
              if (options.typecheck.includes('all'))
×
336
                failures = { includes: () => true } as any as DiagnosticCategory[]
×
337
            else
×
338
              // Default behavior: fail on errors
×
339
              failures.push(DiagnosticCategory.Error)
×
340
            count := diagnostics.filter((d) => failures.includes(d.category)).length
×
341
            if count
×
342
              reason :=
×
343
                (count is diagnostics# ? count : `${count} out of ${diagnostics#}`)
×
344
              throw new Error `Aborting build because of ${reason} TypeScript diagnostic${diagnostics.length > 1 ? 's' : ''} above`
×
345

×
346
        if options.emitDeclaration
×
347
          if meta.framework is 'esbuild' and not esbuildOptions.outdir
×
348
            throw new Error "Civet unplugin's `emitDeclaration` requires esbuild's `outdir` option to be set;"
×
349

×
350
          // Removed duplicate slashed (`\`) versions of the same file for emit
×
351
          for file of fsMap.keys()
×
352
            slashed := slash file
×
353
            unless file is slashed
×
354
              fsMap.delete slashed
×
355

×
356
          for file of fsMap.keys()
×
357
            sourceFile := program.getSourceFile(file)!
×
358
            program.emit
×
359
              sourceFile
×
360
              (filePath, content) =>
×
361
                if options.declarationExtension?
×
362
                  if filePath.endsWith '.d.ts'
×
363
                    filePath = filePath[< -5]
×
364
                  else
×
365
                    console.log `WARNING: No .d.ts extension in ${filePath}`
×
366
                  if filePath.endsWith civetSuffix
×
367
                    filePath = filePath[< -civetSuffix#]
×
368
                  else
×
369
                    console.log `WARNING: No .civet extension in ${filePath}`
×
370
                  filePath += options.declarationExtension
×
371

×
372
                pathFromDistDir .= path.relative
×
373
                  compilerOptions.outDir ?? process.cwd()
×
374
                  filePath
×
375

×
376
                this.emitFile
×
377
                  source: content
×
378
                  fileName: pathFromDistDir
×
379
                  type: 'asset'
×
380
              undefined
×
381
              true // emitDtsOnly
×
382
              undefined
×
383
              // @ts-ignore @internal interface
×
384
              true // forceDtsEmit
×
385

×
386
    resolveId(id, importer, options)
×
387
      id = aliasResolver id if aliasResolver?
×
388
      if (/\0/.test(id)) return null
×
389

×
390
      // Remove query/hash postfix to get actual path
×
391
      {filename, postfix} := extractCivetFilename id, outExt
×
392

×
393
      resolved .=
×
394
        if path.isAbsolute filename
×
395
          resolveAbsolutePath rootDir, filename, implicitExtension
×
396
        else
×
397
          path.resolve path.dirname(importer ?? ''), filename
×
398
      if (!resolved) return null
×
399

×
400
      // Implicit .civet extension
×
401
      unless resolved.endsWith civetSuffix
×
402
        if (!implicitExtension) return null
×
403
        implicitId := implicitCivet resolved
×
404
        if (!implicitId) return null
×
405
        resolved = implicitId
×
406

×
407
      // Tell Vite that this is a virtual module during dependency scanning
×
408
      if (options as! {scan?: boolean}).scan and meta.framework is 'vite'
×
409
        resolved = `\0${resolved}`
×
410

×
411
      // Add back the original postfix at the end
×
412
      return resolved + outExt + postfix
×
413

×
414
    loadInclude(id)
×
415
      extractCivetFilename(id, outExt).filename.endsWith civetSuffix
×
416

×
417
    async load(id)
×
418
      {filename} .= extractCivetFilename id, outExt
×
419
      return null unless filename.endsWith civetSuffix
×
420

×
421
      filename = path.resolve rootDir, filename
×
422
      @addWatchFile filename
×
423

×
424
      let mtime: number?, cached: CacheEntry?, resolve: =>?
×
425
      if cache?
×
426
        try
×
427
          mtime = fs.promises.stat(filename) |> await |> .mtimeMs
×
428
        // If we fail to stat file, ignore cache
×
429
        if mtime?
×
430
          cached = cache.get filename
×
431
          if cached and cached.mtime is mtime
×
432
            // If the file is currently being compiled, wait for it to finish
×
433
            await cached.promise if cached.promise
×
434
            if result? := cached.result
×
435
              return result
×
436
          // We're the first to compile this file with this mtime
×
437
          promise := new Promise<void> (r): void => resolve = r
×
438
          cache.set filename, cached = {mtime, promise}
×
439
      finally resolve?()
×
440

×
441
      let compiled: string
×
442
      let sourceMap: SourceMap | string | undefined
×
443
      civetOptions := {
×
444
        ...compileOptions
×
445
        filename: id
×
446
        errors: []
×
447
      }
×
448
      function checkErrors
×
449
        if civetOptions.errors#
×
450
          throw new civet.ParseErrors civetOptions.errors
×
451

×
NEW
452
      rawCivetSource := decode await fs.promises.readFile filename
×
453
      ast := await civet.compile rawCivetSource, {
×
454
        ...civetOptions
×
455
        ast: true
×
456
      }
×
457
      civetSourceMap := new SourceMap rawCivetSource
×
458

×
459
      if ts is "civet"
×
460
        compiled = await civet.generate ast, {
×
461
          ...civetOptions
×
462
          js: true
×
463
          sourceMap: civetSourceMap
×
464
        }
×
465
        sourceMap = civetSourceMap
×
466
        checkErrors()
×
467
      else
×
468
        compiledTS := await civet.generate ast, {
×
469
          ...civetOptions
×
470
          js: false
×
471
          sourceMap: civetSourceMap
×
472
        }
×
473
        checkErrors()
×
474

×
475
        switch ts
×
476
          when "esbuild"
×
477
            esbuildTransform := import("esbuild") |> await |> .transform
×
478
            result := await esbuildTransform compiledTS,
×
479
              jsx: "preserve"
×
480
              loader: "tsx"
×
481
              sourcefile: id
×
482
              sourcemap: "external"
×
483

×
484
            compiled = result.code
×
485
            sourceMap = result.map
×
486
          when "tsc"
×
487
            tsTranspile := tsPromise! |> await |> .transpileModule
×
488
            result := tsTranspile compiledTS,
×
489
              compilerOptions: compilerOptionsWithSourceMap
×
490

×
491
            compiled = result.outputText
×
492
            sourceMap = result.sourceMapText
×
493
          when "preserve"
×
494
            compiled = compiledTS
×
495
            sourceMap = civetSourceMap
×
496

×
497
      if transformTS
×
498
        // When working with TypeScript, disable rewriteCivetImports and
×
499
        // force rewriteTsImports by rewriting imports again.
×
500
        // See `ModuleSpecifier` in parser.hera
×
501
        for each _spec of lib.gatherRecursive ast, (
×
502
          ($) => ($ as {type: string}).type is "ModuleSpecifier"
×
503
        )
×
504
          spec := _spec as { module?: { token: string, input?: string } }
×
505
          if spec.module?.input
×
506
            spec.module.token = spec.module.input
×
507
            .replace /\.([mc])?ts(['"])$/, ".$1js$2"
×
508

×
509
        compiledTS := await civet.generate ast, {
×
510
          ...civetOptions
×
511
          js: false
×
512
          sourceMap: civetSourceMap
×
513
        }
×
514
        checkErrors()
×
515

×
516
        // Force .tsx extension for type checking purposes.
×
517
        // Otherwise, TypeScript complains about types in .jsx files.
×
518
        tsx := filename + '.tsx'
×
519
        fsMap.set tsx, compiledTS
×
520
        sourceMaps.set tsx, civetSourceMap
×
521
        // Vite and Rollup normalize filenames to use `/` instead of `\`.
×
522
        // We give the TypeScript VFS both versions just in case.
×
523
        slashed := slash tsx
×
524
        unless tsx is slashed
×
525
          fsMap.set slashed, compiledTS
×
526
          sourceMaps.set slashed, civetSourceMap
×
527

×
528
      jsonSourceMap := sourceMap and
×
529
        if sourceMap <? "string"
×
530
          JSON.parse(sourceMap)
×
531
        else
×
532
          sourceMap.json
×
533
            path.relative rootDir, extractCivetFilename(id, outExt).filename
×
534
            path.relative rootDir, id
×
535

×
536
      transformed: TransformResult .=
×
537
        code: compiled
×
538
        map: jsonSourceMap
×
539

×
540
      if options.transformOutput
×
541
        transformed = await options.transformOutput transformed.code, id
×
542

×
543
      if cached?
×
544
        cached.result = transformed
×
545
        delete cached.promise
×
546

×
547
      return transformed
×
548

×
549
    esbuild: {
×
550
      config(options: BuildOptions): void
×
551
        esbuildOptions = options
×
552
    }
×
553
    vite: {
×
554
      config(config: UserConfig): void
×
555
        rootDir = path.resolve process.cwd(), config.root ?? ''
×
556

×
557
        if implicitExtension
×
558
          config.resolve ??= {}
×
559
          config.resolve.extensions ??= DEFAULT_EXTENSIONS
×
560
          config.resolve.extensions.push '.civet'
×
561
      async transformIndexHtml(html)
×
562
        html.replace /<!--[^]*?-->|<[^<>]*>/g, (tag) =>
×
563
          tag.replace /<\s*script\b[^<>]*>/gi, (script) =>
×
564
            // https://html.spec.whatwg.org/multipage/syntax.html#attributes-2
×
565
            script.replace
×
566
              /([:_\p{ID_Start}][:\p{ID_Continue}]*)(\s*=\s*("[^"]*"|'[^']*'|[^\s"'=<>`]*))?/gu
×
567
              (attr, name, value) =>
×
568
                name.toLowerCase() === 'src' && value
×
569
                  ? attr.replace(
×
570
                      /(\.civet)(['"]?)$/,
×
571
                      (_, extension, endQuote) =>
×
572
                        `${extension}${outExt}?transform${endQuote}`
×
573
                    )
×
574
                  : attr
×
575
      handleHotUpdate({ file, server, modules })
×
576
        // `file` is an absolute path to the changed file on disk,
×
577
        // so for our case it should end with .civet extension
×
578
        return unless file.endsWith '.civet'
×
579
        // Convert into path as would be output by `resolveId`
×
580
        resolvedId := slash path.resolve(file) + outExt
×
581
        // Check for module with this name
×
582
        module := server.moduleGraph.getModuleById resolvedId
×
583
        if module
×
584
          // Invalidate modules depending on this one
×
585
          server.moduleGraph.onFileChange resolvedId
×
586
          // Hot reload this module
×
587
          return [ ...modules, module ]
×
588
        modules
×
589
    }
×
590

×
591
    rspack(compiler)
×
592
      if implicitExtension
×
593
        compiler.options ?= {}
×
594
        compiler.options.resolve ?= {}
×
595
        // Default from https://rspack.dev/config/resolve#resolveextensions
×
596
        compiler.options.resolve.extensions ?= ['', '.js', '.json', '.wasm']
×
597
        compiler.options.resolve.extensions.unshift ".civet"
×
598
    webpack(compiler)
×
599
      if implicitExtension
×
600
        compiler.options ?= {}
×
601
        compiler.options.resolve ?= {}
×
602
        // Default from https://webpack.js.org/configuration/resolve/#resolveextensions
×
603
        compiler.options.resolve.extensions ?= ['', '.js', '.json', '.wasm']
×
604
        compiler.options.resolve.extensions.unshift ".civet"
×
605
      aliasResolver = (id) =>
×
606
        // Based on normalizeAlias from
×
607
        // https://github.com/webpack/enhanced-resolve/blob/72999caf002f6f7bb4624e65fdeb7ba980b11e24/lib/ResolverFactory.js#L158
×
608
        // and AliasPlugin from
×
609
        // https://github.com/webpack/enhanced-resolve/blob/72999caf002f6f7bb4624e65fdeb7ba980b11e24/lib/AliasPlugin.js
×
610
        for key, value in compiler.options.resolve.alias
×
611
          if key.endsWith '$'
×
612
            if id is key[...-1]
×
613
              return value <? 'string' ? value : '\0'
×
614
          else
×
615
            if id is key or id.startsWith key + '/'
×
616
              return '\0' unless value <? 'string'
×
617
              return value + id[key.length..]
×
618
        id
×
619
  }
×
620

1✔
621
var unplugin = createUnplugin(rawPlugin)
1✔
622
export default unplugin
1✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc