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

DanielXMoore / Civet / 15086317916

17 May 2025 02:51PM UTC coverage: 91.65% (-0.01%) from 91.66%
15086317916

push

github

web-flow
Merge pull request #1733 from adam2am/main

3645 of 3964 branches covered (91.95%)

Branch coverage included in aggregate %.

9 of 38 new or added lines in 1 file covered. (23.68%)

18823 of 20551 relevant lines covered (91.59%)

16344.96 hits per line

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

12.52
/source/unplugin/unplugin.civet
1
import { type TransformResult, createUnplugin } from 'unplugin'
1✔
2
import civet, { 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✔
NEW
67
function extractCivetFilename(id: string, outputExtension: string): {filename: string, postfix: string}
×
NEW
68
  postfix .= ''
×
NEW
69
  filename .= id.replace postfixRE, (match) =>
×
70
    postfix = match
×
71
    ''
×
NEW
72
  // Normally the outputExtension (.jsx/.tsx by default) should be present,
×
NEW
73
  // but sometimes (e.g. esbuild's alias feature) load directly without resolve
×
NEW
74
  if filename.endsWith outputExtension
×
NEW
75
    filename = filename[< -outputExtension#]
×
NEW
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
        }
×
249
        system.readFile = (filename: string, encoding = '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]
×
273
          rawCivetSource := fs.readFileSync civetFilename,
×
274
            encoding: encoding as BufferEncoding
×
275
          { code: compiledTS, sourceMap } := civet.compile rawCivetSource, {
×
276
            ...tsCompileOptions
×
277
            filename
×
278
            js: false
×
279
            sourceMap: true
×
280
            sync: true // TS readFile API seems to need to be synchronous
×
281
          }
×
282
          fsMap.set filename, compiledTS
×
283
          sourceMaps.set filename, sourceMap
×
284
          return compiledTS
×
285

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

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

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

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

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

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

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

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

×
347
        if options.emitDeclaration
×
348
          if meta.framework is 'esbuild' and not esbuildOptions.outdir
×
349
            console.log "WARNING: Civet unplugin's `emitDeclaration` requires esbuild's `outdir` option to be set;"
×
350

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
453
      rawCivetSource := await fs.promises.readFile filename, 'utf-8'
×
454
      ast := await civet.compile rawCivetSource, {
×
455
        ...civetOptions
×
456
        ast: true
×
457
      }
×
458
      civetSourceMap := new SourceMap rawCivetSource
×
459

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

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

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

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

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

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

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

×
529
      jsonSourceMap := sourceMap and
×
530
        if sourceMap <? "string"
×
531
          JSON.parse(sourceMap)
×
532
        else
×
533
          sourceMap.json
×
534
            path.relative rootDir, id.replace /\.[jt]sx$/, ''
×
535
            path.relative rootDir, id
×
536

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

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

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

×
548
      return transformed
×
549

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

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

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

1✔
622
var unplugin = createUnplugin(rawPlugin)
1✔
623
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