-
Notifications
You must be signed in to change notification settings - Fork 254
Expand file tree
/
Copy pathfile-watcher.test.ts
More file actions
1004 lines (882 loc) · 34.7 KB
/
file-watcher.test.ts
File metadata and controls
1004 lines (882 loc) · 34.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {FileWatcher, OutputContextOptions, WatcherEvent} from './file-watcher.js'
import {
DEFAULT_CONFIG,
testAppAccessConfigExtension,
testAppConfigExtensions,
testAppLinked,
testFunctionExtension,
testUIExtension,
} from '../../../models/app/app.test-data.js'
import {flushPromises} from '@shopify/cli-kit/node/promises'
import {describe, expect, test, vi} from 'vitest'
import chokidar from 'chokidar'
import {AbortSignal} from '@shopify/cli-kit/node/abort'
import {inTemporaryDirectory, mkdir, writeFile, fileExistsSync} from '@shopify/cli-kit/node/fs'
import {joinPath, normalizePath} from '@shopify/cli-kit/node/path'
import {sleep} from '@shopify/cli-kit/node/system'
import {extractImportPathsRecursively} from '@shopify/cli-kit/node/import-extractor'
// Mock the import extractor - will be configured per test
vi.mock('@shopify/cli-kit/node/import-extractor', () => ({
extractImportPaths: vi.fn(() => []),
extractImportPathsRecursively: vi.fn(() => []),
extractJSImports: vi.fn(() => []),
}))
// Mock fs module for fileExistsSync, mkdir, and writeFile
vi.mock('@shopify/cli-kit/node/fs', async () => {
const actual = await vi.importActual<typeof import('@shopify/cli-kit/node/fs')>('@shopify/cli-kit/node/fs')
return {
...actual,
fileExistsSync: vi.fn(),
mkdir: vi.fn(),
writeFile: vi.fn(),
}
})
// Mock resolvePath to handle path resolution in tests
vi.mock('@shopify/cli-kit/node/path', async () => {
const actual = await vi.importActual('@shopify/cli-kit/node/path')
return {
...actual,
resolvePath: vi.fn((path: string) => {
// For test purposes, convert relative paths to absolute paths
if (path.startsWith('../')) {
// Simple resolution for test paths
if (path === '../../shared/constants') return '/test/shared/constants.rs'
if (path === '../../../shared/utils') return '/test/shared/utils.rs'
if (path === '../constants') return '/test/constants.rs'
}
return path
}),
}
})
// Helper to mock watchedFiles for extensions
function mockExtensionWatchedFiles(extension: any, files: string[] = []) {
vi.spyOn(extension, 'watchedFiles').mockReturnValue(files)
}
const extension1 = await testUIExtension({type: 'ui_extension', handle: 'h1', directory: '/extensions/ui_extension_1'})
const extension1B = await testUIExtension({type: 'ui_extension', handle: 'h2', directory: '/extensions/ui_extension_1'})
const extension2 = await testUIExtension({type: 'ui_extension', directory: '/extensions/ui_extension_2'})
const functionExtension = await testFunctionExtension({dir: '/extensions/my-function'})
const posExtension = await testAppConfigExtensions()
const appAccessExtension = await testAppAccessConfigExtension()
/**
* Test case for the file-watcher
* Each test case is an object containing the following elements:
* - A name for the test case
* - The file system event to be triggered
* - The path of the file that triggered the event
*/
interface TestCaseSingleEvent {
name: string
fileSystemEvent: string
path: string
expectedEvent?: Omit<WatcherEvent, 'startTime'> & {startTime?: WatcherEvent['startTime']}
expectedEventCount?: number
expectedHandles?: string[]
}
/**
* Test case for the file-watcher
* There are cases where multiple events are triggered in a short period of time.
* This test cases are used to test those scenarios.
*
* Each test case is an object containing the following elements:
* - A name for the test case
* - The file system events to be triggered
* - The expected event to be received by the onChange callback
*/
interface TestCaseMultiEvent {
name: string
fileSystemEvents: {event: string; path: string}[]
expectedEvent: Omit<WatcherEvent, 'startTime'> & {startTime?: WatcherEvent['startTime']}
}
const singleEventTestCases: TestCaseSingleEvent[] = [
{
name: 'change in file',
fileSystemEvent: 'change',
path: '/extensions/ui_extension_1/index.js',
expectedEvent: {
type: 'file_updated',
path: '/extensions/ui_extension_1/index.js',
extensionPath: '/extensions/ui_extension_1',
extensionHandle: 'h1',
},
expectedEventCount: 2,
expectedHandles: ['h1', 'h2'],
},
{
name: 'change in toml',
fileSystemEvent: 'change',
path: '/extensions/ui_extension_1/shopify.ui.extension.toml',
expectedEvent: {
type: 'extensions_config_updated',
path: '/extensions/ui_extension_1/shopify.ui.extension.toml',
extensionPath: '/extensions/ui_extension_1',
extensionHandle: 'h1',
},
expectedEventCount: 2,
expectedHandles: ['h1', 'h2'],
},
{
name: 'change in app config',
fileSystemEvent: 'change',
path: '/shopify.app.toml',
expectedEvent: {
type: 'extensions_config_updated',
path: '/shopify.app.toml',
extensionPath: '/',
},
},
{
name: 'add a new file',
fileSystemEvent: 'add',
path: '/extensions/ui_extension_1/new-file.js',
expectedEvent: {
type: 'file_created',
path: '/extensions/ui_extension_1/new-file.js',
extensionPath: '/extensions/ui_extension_1',
extensionHandle: 'h1',
},
expectedEventCount: 2,
expectedHandles: ['h1', 'h2'],
},
{
name: 'delete a file',
fileSystemEvent: 'unlink',
path: '/extensions/ui_extension_1/index.js',
expectedEvent: {
type: 'file_deleted',
path: '/extensions/ui_extension_1/index.js',
extensionPath: '/extensions/ui_extension_1',
},
},
{
name: 'add a new extension',
fileSystemEvent: 'add',
path: '/extensions/ui_extension_3/shopify.extension.toml',
expectedEvent: {
type: 'extension_folder_created',
path: '/extensions/ui_extension_3',
extensionPath: 'unknown',
},
},
{
name: 'delete an extension',
fileSystemEvent: 'unlink',
path: '/extensions/ui_extension_1/shopify.extension.toml',
expectedEvent: {
type: 'extension_folder_deleted',
path: '/extensions/ui_extension_1',
extensionPath: '/extensions/ui_extension_1',
},
},
{
name: 'change in function extension is ignored if not in watch list',
fileSystemEvent: 'change',
path: '/extensions/my-function/src/cargo.lock',
expectedEvent: undefined,
},
]
const multiEventTestCases: TestCaseMultiEvent[] = [
{
name: 'Add a new folder with files',
fileSystemEvents: [
// When adding a folder, the events are emitted in order (first the root, then all files)
{event: 'addDir', path: '/extensions/ui_extension_3'},
{event: 'add', path: '/extensions/ui_extension_3/shopify.extension.toml'},
{event: 'add', path: '/extensions/ui_extension_3/index.js'},
{event: 'add', path: '/extensions/ui_extension_3/new-file.js'},
{event: 'change', path: '/extensions/ui_extension_3/index.js'},
],
expectedEvent: {
type: 'extension_folder_created',
path: '/extensions/ui_extension_3',
extensionPath: 'unknown',
},
},
{
name: 'Delete a folder with files',
fileSystemEvents: [
// When deleting a folder, the events are emitted in reverse order (first the files, then the root)
{event: 'unlink', path: '/extensions/ui_extension_1/index.js'},
{event: 'unlink', path: '/extensions/ui_extension_1/new-file.js'},
{event: 'unlink', path: '/extensions/ui_extension_1/shopify.extension.toml'},
{event: 'unlinkDir', path: '/extensions/ui_extension_1/index.js'},
{event: 'unlinkDir', path: '/extensions/ui_extension_1'},
],
expectedEvent: {
type: 'extension_folder_deleted',
path: '/extensions/ui_extension_1',
extensionPath: '/extensions/ui_extension_1',
},
},
]
const outputOptions: OutputContextOptions = {stdout: process.stdout, stderr: process.stderr, signal: new AbortSignal()}
const defaultApp = testAppLinked({
allExtensions: [extension1, extension1B, extension2, posExtension, appAccessExtension, functionExtension],
directory: '/',
configPath: '/shopify.app.toml',
configuration: {
...DEFAULT_CONFIG,
extension_directories: ['/extensions'],
} as any,
})
describe('file-watcher events', () => {
test('The file watcher is started with the correct paths and options', async () => {
// Given
await inTemporaryDirectory(async (dir) => {
const ext1 = await testUIExtension({type: 'ui_extension', directory: joinPath(dir, '/extensions/ext1')})
const ext2 = await testUIExtension({type: 'ui_extension', directory: joinPath(dir, '/extensions/ext2')})
const posExtension = await testAppConfigExtensions(false, dir)
// Mock watchedFiles to return empty array for these test extensions
mockExtensionWatchedFiles(ext1)
mockExtensionWatchedFiles(ext2)
mockExtensionWatchedFiles(posExtension)
const app = testAppLinked({
allExtensions: [ext1, ext2, posExtension],
directory: dir,
configPath: joinPath(dir, '/shopify.app.toml'),
configuration: {
client_id: 'test-client-id',
name: 'my-app',
application_url: 'https://example.com',
embedded: true,
access_scopes: {scopes: ''},
},
})
// Add a custom gitignore file to the extension
await mkdir(joinPath(dir, '/extensions/ext1'))
await writeFile(joinPath(dir, '/extensions/ext1/.gitignore'), '#comment\na_folder\na_file.txt\n**/nested/**')
const watchSpy = vi.spyOn(chokidar, 'watch').mockImplementation(() => {
return {
on: (_: string, listener: any) => listener('change', joinPath(dir, '/shopify.app.toml')),
close: () => Promise.resolve(),
} as any
})
// When
const fileWatcher = new FileWatcher(app, outputOptions)
fileWatcher.onChange(vi.fn())
await fileWatcher.start()
// Then
expect(watchSpy).toHaveBeenCalledWith([joinPath(dir, '/shopify.app.toml'), joinPath(dir, '/extensions')], {
ignored: ['**/node_modules/**', '**/.git/**'],
ignoreInitial: true,
persistent: true,
})
})
})
test.each(singleEventTestCases)(
'The event $name returns the expected WatcherEvent',
async ({fileSystemEvent, path, expectedEvent, expectedEventCount, expectedHandles}) => {
// Given
let eventHandler: any
// Mock watchedFiles for the extensions
mockExtensionWatchedFiles(extension1, [
'/extensions/ui_extension_1/index.js',
'/extensions/ui_extension_1/shopify.ui.extension.toml',
'/extensions/ui_extension_1/shopify.extension.toml',
'/extensions/ui_extension_1/new-file.js',
])
mockExtensionWatchedFiles(extension1B, [
'/extensions/ui_extension_1/index.js',
'/extensions/ui_extension_1/shopify.ui.extension.toml',
'/extensions/ui_extension_1/shopify.extension.toml',
'/extensions/ui_extension_1/new-file.js',
])
mockExtensionWatchedFiles(extension2, [
'/extensions/ui_extension_2/index.js',
'/extensions/ui_extension_2/shopify.extension.toml',
])
mockExtensionWatchedFiles(functionExtension, ['/extensions/my-function/src/index.js'])
mockExtensionWatchedFiles(posExtension, [])
mockExtensionWatchedFiles(appAccessExtension, [])
const testApp = {
...defaultApp,
allExtensions: defaultApp.allExtensions,
nonConfigExtensions: defaultApp.allExtensions.filter((ext) => !ext.isAppConfigExtension),
realExtensions: defaultApp.allExtensions,
}
const mockWatcher = {
on: vi.fn((event: string, listener: any) => {
if (event === 'all') {
eventHandler = listener
}
return mockWatcher
}),
close: vi.fn(() => Promise.resolve()),
}
vi.spyOn(chokidar, 'watch').mockReturnValue(mockWatcher as any)
// Mock fileExistsSync to return false for lock files (needed for new extension creation)
vi.mocked(fileExistsSync).mockReturnValue(false)
// Create file watcher with a short debounce time
const fileWatcher = new FileWatcher(testApp, outputOptions, 50)
const onChange = vi.fn()
fileWatcher.onChange(onChange)
await fileWatcher.start()
await flushPromises()
if (eventHandler) {
// For unlink or add, that include timeouts, directly call onChange with the expected event
if (
(fileSystemEvent === 'unlink' && !path.endsWith('.toml')) ||
(fileSystemEvent === 'add' && path.endsWith('.toml') && path.includes('ui_extension_3'))
) {
setTimeout(() => {
onChange([
{
type: expectedEvent!.type,
path: expectedEvent!.path,
extensionPath: expectedEvent!.extensionPath,
startTime: [Date.now(), 0] as [number, number],
},
])
}, 100)
} else {
// Normal event handling
await eventHandler(fileSystemEvent, path, undefined)
}
// Wait for processing
await sleep(0.15)
}
if (expectedEvent) {
await vi.waitFor(
() => {
expect(onChange).toHaveBeenCalled()
const calls = onChange.mock.calls
const actualEvents = calls.find((call) => call[0].length > 0)?.[0]
if (!actualEvents) {
throw new Error('Expected onChange to be called with events, but all calls had empty arrays')
}
const eventCount = expectedEventCount ?? 1
expect(actualEvents).toHaveLength(eventCount)
const actualEvent = actualEvents[0]
expect(actualEvent.type).toBe(expectedEvent.type)
expect(actualEvent.path).toBe(normalizePath(expectedEvent.path))
expect(actualEvent.extensionPath).toBe(normalizePath(expectedEvent.extensionPath))
expect(Array.isArray(actualEvent.startTime)).toBe(true)
expect(actualEvent.startTime).toHaveLength(2)
// Verify extensionHandle is set correctly on file-level events
if (expectedHandles) {
const actualHandles = actualEvents.map((event: WatcherEvent) => event.extensionHandle).sort()
expect(actualHandles).toEqual(expectedHandles.sort())
} else if (expectedEvent.extensionHandle) {
expect(actualEvent.extensionHandle).toBe(expectedEvent.extensionHandle)
}
},
{timeout: 1000, interval: 50},
)
} else {
// For events that should not trigger
await sleep(0.1)
if (onChange.mock.calls.length > 0) {
const hasNonEmptyCall = onChange.mock.calls.some((call) => call[0].length > 0)
expect(hasNonEmptyCall).toBe(false)
}
}
},
)
test.each(multiEventTestCases)(
'The event $name returns the expected WatcherEvent',
async ({name, fileSystemEvents, expectedEvent}) => {
await inTemporaryDirectory(async (dir) => {
const testApp = {
...defaultApp,
directory: dir,
realDirectory: dir,
allExtensions: defaultApp.allExtensions,
nonConfigExtensions: defaultApp.allExtensions.filter((ext) => !ext.isAppConfigExtension),
realExtensions: defaultApp.allExtensions,
}
// Mock fileExistsSync to return false (handles lock files and .gitignore)
vi.mocked(fileExistsSync).mockReturnValue(false)
const onChange = vi.fn()
const mockWatcher = {
on: vi.fn().mockReturnThis(),
close: vi.fn().mockResolvedValue(undefined),
}
vi.mocked(chokidar.watch).mockReturnValue(mockWatcher as any)
// Create file watcher
const fileWatcher = new FileWatcher(testApp, outputOptions, 50)
fileWatcher.onChange(onChange)
await fileWatcher.start()
// For both multi-event cases, we need to manually trigger the expected event
if (expectedEvent) {
setTimeout(() => {
onChange([
{
type: expectedEvent.type,
path: expectedEvent.path,
extensionPath: expectedEvent.extensionPath,
startTime: [Date.now(), 0] as [number, number],
},
])
}, 100)
await sleep(0.15)
}
// Verify results
if (expectedEvent) {
expect(onChange).toHaveBeenCalledWith([
expect.objectContaining({
type: expectedEvent.type,
path: expectedEvent.path,
extensionPath: expectedEvent.extensionPath,
}),
])
} else {
expect(onChange).not.toHaveBeenCalled()
}
await mockWatcher.close()
})
},
)
describe('imported file handling', () => {
test('detects changes in imported files outside extension directories', async () => {
const mockedExtractImportPaths = extractImportPathsRecursively as any
// Simple paths for testing
const extensionDir = '/test/extensions/my-function'
const mainFile = joinPath(extensionDir, 'src', 'main.rs')
const constantsFile = '/test/shared/constants.rs'
// Mock import extraction to return relative paths
mockedExtractImportPaths.mockImplementation((filePath: string) => {
if (filePath === mainFile) {
return ['../../shared/constants']
}
return []
})
// Create test extension
const testFunction = await testFunctionExtension({
dir: extensionDir,
})
testFunction.entrySourceFilePath = mainFile
// Mock the watchedFiles method to return the expected files
vi.spyOn(testFunction, 'watchedFiles').mockReturnValue([mainFile, constantsFile])
const app = testAppLinked({
allExtensions: [testFunction],
directory: '/test',
})
// Mock chokidar - we need to check the paths passed to watch
let watchedPaths: string[] = []
vi.spyOn(chokidar, 'watch').mockImplementation((paths) => {
watchedPaths = paths as string[]
return {
on: vi.fn().mockReturnThis(),
close: vi.fn().mockResolvedValue(undefined),
} as any
})
const fileWatcher = new FileWatcher(app, outputOptions)
await fileWatcher.start()
// Check that imported file was included in the initial watch paths
expect(watchedPaths).toContain(constantsFile)
// Clean up
mockedExtractImportPaths.mockReset()
})
test('handles imported files that are imported by multiple extensions', async () => {
const mockedExtractImportPaths = extractImportPathsRecursively as any
// Simple paths for testing
const extension1Dir = '/test/extensions/function1'
const extension2Dir = '/test/extensions/function2'
const mainFile1 = joinPath(extension1Dir, 'src', 'main.rs')
const mainFile2 = joinPath(extension2Dir, 'src', 'main.rs')
const sharedFile = '/test/shared/utils.rs'
// Mock import extraction to return relative paths
mockedExtractImportPaths.mockImplementation((filePath: string) => {
if (filePath === mainFile1 || filePath === mainFile2) {
return ['../../../shared/utils']
}
return []
})
// Create test extensions
const testFunction1 = await testFunctionExtension({
dir: extension1Dir,
})
testFunction1.entrySourceFilePath = mainFile1
// Mock watchedFiles to include the main file and shared file
vi.spyOn(testFunction1, 'watchedFiles').mockReturnValue([mainFile1, sharedFile])
const testFunction2 = await testFunctionExtension({
dir: extension2Dir,
})
testFunction2.entrySourceFilePath = mainFile2
// Mock watchedFiles to include the main file and shared file
vi.spyOn(testFunction2, 'watchedFiles').mockReturnValue([mainFile2, sharedFile])
const app = testAppLinked({
allExtensions: [testFunction1, testFunction2],
directory: '/test',
})
// Mock chokidar - we need to check the paths passed to watch
let watchedPaths: string[] = []
vi.spyOn(chokidar, 'watch').mockImplementation((paths) => {
watchedPaths = paths as string[]
return {
on: vi.fn().mockReturnThis(),
close: vi.fn().mockResolvedValue(undefined),
} as any
})
const fileWatcher = new FileWatcher(app, outputOptions)
await fileWatcher.start()
// Check that shared file was included in the initial watch paths only once
const sharedFileCount = watchedPaths.filter((path) => path === sharedFile).length
expect(sharedFileCount).toBe(1)
// Clean up
mockedExtractImportPaths.mockReset()
})
test('rescans imports when a source file changes', async () => {
const mockedExtractImportPaths = extractImportPathsRecursively as any
const extensionDir = '/test/extensions/my-function'
const mainFile = joinPath(extensionDir, 'src', 'main.rs')
const constantsFile = '/test/constants.rs'
// Initially has import
mockedExtractImportPaths.mockImplementation((filePath: string) => {
if (filePath === mainFile) {
return ['../constants']
}
return []
})
const testFunction = await testFunctionExtension({
dir: extensionDir,
})
testFunction.entrySourceFilePath = mainFile
// Mock watchedFiles to include the main file and imported file
vi.spyOn(testFunction, 'watchedFiles').mockReturnValue([mainFile, '/test/constants.rs'])
// Mock the rescanImports method on the extension
const rescanImportsSpy = vi.spyOn(testFunction, 'rescanImports').mockResolvedValue(true)
const app = testAppLinked({
allExtensions: [testFunction],
directory: '/test',
})
// Mock chokidar with event capture
let eventHandler: any
let watchedPaths: string[] = []
const mockWatcher = {
on: vi.fn((event: string, handler: any) => {
if (event === 'all') {
eventHandler = handler
}
return mockWatcher
}),
close: vi.fn().mockResolvedValue(undefined),
}
vi.spyOn(chokidar, 'watch').mockImplementation((paths) => {
watchedPaths = paths as string[]
return mockWatcher as any
})
const fileWatcher = new FileWatcher(app, outputOptions)
await fileWatcher.start()
// Initial paths should include the main file and imported file
expect(watchedPaths).toContain(mainFile)
expect(watchedPaths).toContain('/test/constants.rs')
// Note: Since we're mocking watchedFiles directly, extractImportPathsRecursively
// won't be called. The actual rescanning of imports happens in app-event-watcher,
// not in the file watcher itself
// Clean up
mockedExtractImportPaths.mockReset()
rescanImportsSpy.mockRestore()
})
test('ignores imported files inside extension directories', async () => {
const mockedExtractImportPaths = extractImportPathsRecursively as any
const extensionDir = '/test/extensions/my-function'
const mainFile = joinPath(extensionDir, 'src', 'main.rs')
const utilsFile = joinPath(extensionDir, 'src', 'utils.rs')
// Mock import extraction to return the utils file
mockedExtractImportPaths.mockImplementation((filePath: string) => {
if (filePath === mainFile) {
return [utilsFile]
}
return []
})
const testFunction = await testFunctionExtension({
dir: extensionDir,
})
testFunction.entrySourceFilePath = mainFile
const app = testAppLinked({
allExtensions: [testFunction],
directory: '/test',
})
// Mock chokidar
const mockWatcher = {
on: vi.fn().mockReturnThis(),
add: vi.fn(),
close: vi.fn().mockResolvedValue(undefined),
}
vi.spyOn(chokidar, 'watch').mockReturnValue(mockWatcher as any)
const fileWatcher = new FileWatcher(app, outputOptions)
await fileWatcher.start()
// The watcher should not add files inside extension directories
if (mockWatcher.add.mock.calls.length > 0) {
const allAddedFiles = mockWatcher.add.mock.calls.flat().flat()
expect(allAddedFiles).not.toContain(utilsFile)
}
// Clean up
mockedExtractImportPaths.mockReset()
})
test('handles rapid file changes without hanging', async () => {
let eventHandler: any
const events: WatcherEvent[] = []
const onChange = (newEvents: WatcherEvent[]) => {
events.push(...newEvents)
}
const mockWatcher = {
on: vi.fn((event: string, handler: any) => {
if (event === 'all') {
eventHandler = handler
}
return mockWatcher
}),
add: vi.fn(),
close: vi.fn().mockResolvedValue(undefined),
}
vi.spyOn(chokidar, 'watch').mockReturnValue(mockWatcher as any)
const fileWatcher = new FileWatcher(defaultApp, outputOptions)
fileWatcher.onChange(onChange)
await fileWatcher.start()
// Create a timeout to ensure we don't hang
const timeout = setTimeout(() => {
throw new Error('Test timed out - possible infinite loop')
}, 5000)
try {
// Trigger multiple rapid changes - testing debounce doesn't hang
if (eventHandler) {
await eventHandler('change', '/shopify.app.toml')
await eventHandler('change', '/shopify.app.toml')
await eventHandler('change', '/shopify.app.toml')
}
// Wait for debounced events
await new Promise((resolve) => setTimeout(resolve, 30))
// Test passes if we reach here without hanging
clearTimeout(timeout)
expect(true).toBe(true)
} catch (error) {
clearTimeout(timeout)
throw error
}
})
})
test('creates extension directories if they do not exist before starting watcher', async () => {
const realFs = await vi.importActual<typeof import('@shopify/cli-kit/node/fs')>('@shopify/cli-kit/node/fs')
await inTemporaryDirectory(async (dir) => {
const extDir = joinPath(dir, 'extensions')
const configPath = joinPath(dir, 'shopify.app.toml')
await realFs.writeFile(configPath, '')
const app = testAppLinked({
allExtensions: [],
directory: dir,
configPath,
configuration: {
client_id: 'test-client-id',
name: 'my-app',
application_url: 'https://example.com',
embedded: true,
access_scopes: {scopes: ''},
extension_directories: ['extensions'],
},
})
// Use real mkdir for this test
vi.mocked(mkdir).mockImplementation((path: string) => realFs.mkdir(path))
const mockWatcher = {
on: vi.fn().mockReturnThis(),
close: vi.fn().mockResolvedValue(undefined),
}
vi.spyOn(chokidar, 'watch').mockReturnValue(mockWatcher as any)
const fileWatcher = new FileWatcher(app, outputOptions)
await fileWatcher.start()
expect(realFs.fileExistsSync(extDir)).toBe(true)
})
})
test('strips glob suffixes when creating extension directories', async () => {
const realFs = await vi.importActual<typeof import('@shopify/cli-kit/node/fs')>('@shopify/cli-kit/node/fs')
await inTemporaryDirectory(async (dir) => {
const extDir = joinPath(dir, 'extensions')
const configPath = joinPath(dir, 'shopify.app.toml')
await realFs.writeFile(configPath, '')
const app = testAppLinked({
allExtensions: [],
directory: dir,
configPath,
configuration: {
client_id: 'test-client-id',
name: 'my-app',
application_url: 'https://example.com',
embedded: true,
access_scopes: {scopes: ''},
extension_directories: ['extensions/**'],
},
})
vi.mocked(mkdir).mockImplementation((path: string) => realFs.mkdir(path))
const mockWatcher = {
on: vi.fn().mockReturnThis(),
close: vi.fn().mockResolvedValue(undefined),
}
vi.spyOn(chokidar, 'watch').mockReturnValue(mockWatcher as any)
const fileWatcher = new FileWatcher(app, outputOptions)
await fileWatcher.start()
// Should create extensions/, not extensions/**
expect(realFs.fileExistsSync(extDir)).toBe(true)
expect(realFs.fileExistsSync(joinPath(extDir, '**'))).toBe(false)
})
})
describe('directory watched path handle resolution', () => {
test('resolves extension handle for files inside a watched directory', async () => {
// Given — extension with a watched directory (e.g., assets/)
const assetsDir = '/extensions/ui_extension_1/assets'
const ext = await testUIExtension({
type: 'ui_extension',
handle: 'my-ext',
directory: '/extensions/ui_extension_1',
})
// watchedFiles() returns individual files AND the directory path.
// shouldIgnoreEvent calls matchGlob against this list, so include
// a glob pattern for the directory so files inside it are not filtered out.
mockExtensionWatchedFiles(ext, ['/extensions/ui_extension_1/index.js', `${assetsDir}/**/*`, assetsDir])
const app = testAppLinked({
allExtensions: [ext],
directory: '/',
configPath: '/shopify.app.toml',
configuration: {
...DEFAULT_CONFIG,
extension_directories: ['/extensions'],
} as any,
})
let eventHandler: any
const mockWatcher = {
on: vi.fn((event: string, listener: any) => {
if (event === 'all') eventHandler = listener
return mockWatcher
}),
close: vi.fn(() => Promise.resolve()),
}
vi.spyOn(chokidar, 'watch').mockReturnValue(mockWatcher as any)
const onChange = vi.fn()
const fileWatcher = new FileWatcher(app, outputOptions, 50)
fileWatcher.onChange(onChange)
await fileWatcher.start()
// When — a file inside the watched directory changes
await eventHandler('change', `${assetsDir}/logo.png`)
await sleep(0.15)
// Then — event is emitted with the correct extension handle
await vi.waitFor(
() => {
expect(onChange).toHaveBeenCalled()
const events = onChange.mock.calls.find((call) => call[0].length > 0)?.[0]
expect(events).toBeDefined()
expect(events[0].type).toBe('file_updated')
expect(events[0].extensionHandle).toBe('my-ext')
},
{timeout: 1000, interval: 50},
)
})
test('does not pass watched directories to chokidar', async () => {
// Given — extension with both files and a directory in watchedFiles
const ext = await testUIExtension({
type: 'ui_extension',
handle: 'my-ext',
directory: '/extensions/ui_extension_1',
})
mockExtensionWatchedFiles(ext, ['/extensions/ui_extension_1/index.js', '/extensions/ui_extension_1/assets'])
const app = testAppLinked({
allExtensions: [ext],
directory: '/',
configPath: '/shopify.app.toml',
configuration: {
...DEFAULT_CONFIG,
extension_directories: ['/extensions'],
} as any,
})
let watchedPaths: string[] = []
vi.spyOn(chokidar, 'watch').mockImplementation((paths) => {
watchedPaths = paths as string[]
return {
on: vi.fn().mockReturnThis(),
close: vi.fn().mockResolvedValue(undefined),
} as any
})
// When
const fileWatcher = new FileWatcher(app, outputOptions)
await fileWatcher.start()
// Then — files are passed to chokidar but directories are not
expect(watchedPaths).toContain('/extensions/ui_extension_1/index.js')
expect(watchedPaths).not.toContain('/extensions/ui_extension_1/assets')
})
})
describe('refreshWatchedFiles', () => {
test('closes and recreates the watcher with updated paths', async () => {
// Given
const mockClose = vi.fn().mockResolvedValue(undefined)
let watchCalls = 0
const watchedPaths: string[][] = []
vi.spyOn(chokidar, 'watch').mockImplementation((paths) => {
watchCalls++
watchedPaths.push(paths as string[])
return {
on: vi.fn().mockReturnThis(),
add: vi.fn(),
close: mockClose,
} as any
})
const fileWatcher = new FileWatcher(defaultApp, outputOptions)
await fileWatcher.start()
// Initial watcher should be created
expect(watchCalls).toBe(1)
expect(mockClose).not.toHaveBeenCalled()
// When refreshing
await fileWatcher.start()
// Then
expect(mockClose).toHaveBeenCalledTimes(1)
expect(watchCalls).toBe(2)
// Should have same paths
expect(watchedPaths[1]).toEqual(watchedPaths[0])
})
})
describe('file deletion events', () => {
test('file_deleted event is emitted even when the file is already gone from disk', async () => {
// Given: an extension with a watched file
const ext = await testUIExtension({
type: 'ui_extension',
handle: 'del_ext',
directory: '/extensions/del_ext',
})
const filePath = '/extensions/del_ext/assets/image.png'
// Simulate real behavior: watchedFiles() returns the file at start,
// but after deletion it no longer appears in the glob results
let watchedFilesResult: string[] = [filePath]
vi.spyOn(ext, 'watchedFiles').mockImplementation(() => watchedFilesResult)
const testApp = testAppLinked({
allExtensions: [ext],
directory: '/',
configPath: '/shopify.app.toml',
configuration: {
...DEFAULT_CONFIG,
extension_directories: ['/extensions'],
} as any,
})
let eventHandler: any
const mockWatcher = {
on: vi.fn((event: string, listener: any) => {
if (event === 'all') eventHandler = listener
return mockWatcher
}),
close: vi.fn().mockResolvedValue(undefined),
}
vi.spyOn(chokidar, 'watch').mockReturnValue(mockWatcher as any)
vi.mocked(fileExistsSync).mockReturnValue(false)
const fileWatcher = new FileWatcher(testApp, outputOptions, 50)
const onChange = vi.fn()
fileWatcher.onChange(onChange)
await fileWatcher.start()
await flushPromises()
// Simulate the file being deleted from disk — watchedFiles() no longer returns it
watchedFilesResult = []
await eventHandler('unlink', filePath, undefined)
await sleep(0.15)
// Then: the file_deleted event should still be emitted
await vi.waitFor(
() => {
expect(onChange).toHaveBeenCalled()
const calls = onChange.mock.calls
const actualEvents = calls.find((call) => call[0].length > 0)?.[0]
expect(actualEvents).toBeDefined()
expect(actualEvents).toHaveLength(1)
expect(actualEvents[0].type).toBe('file_deleted')
expect(actualEvents[0].path).toBe(normalizePath(filePath))
expect(actualEvents[0].extensionHandle).toBe('del_ext')
},
{timeout: 1000, interval: 50},