This repository has been archived by the owner on May 22, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 35
/
main.test.ts
2936 lines (2474 loc) · 105 KB
/
main.test.ts
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 { mkdir, readFile, rm, symlink, writeFile } from 'fs/promises'
import { dirname, isAbsolute, join, resolve } from 'path'
import { arch, version as nodeVersion, platform } from 'process'
import cpy from 'cpy'
import decompress from 'decompress'
import merge from 'deepmerge'
import { execa, execaNode } from 'execa'
import glob from 'fast-glob'
import isCI from 'is-ci'
import { pathExists } from 'path-exists'
import semver from 'semver'
import { dir as getTmpDir, tmpName } from 'tmp-promise'
import unixify from 'unixify'
import { afterAll, afterEach, beforeAll, describe, expect, test, vi } from 'vitest'
import { ARCHIVE_FORMAT } from '../src/archive.js'
import { ESBUILD_LOG_LIMIT } from '../src/runtimes/node/bundlers/esbuild/bundler.js'
import { NODE_BUNDLER } from '../src/runtimes/node/bundlers/types.js'
import { detectEsModule } from '../src/runtimes/node/utils/detect_es_module.js'
import { MODULE_FORMAT } from '../src/runtimes/node/utils/module_format.js'
import { shellUtils } from '../src/utils/shell.js'
import type { ZipFunctionsOptions } from '../src/zip.js'
import {
BINARY_PATH,
FIXTURES_DIR,
getBundlerNameFromOptions,
getRequires,
importFunctionFile,
unzipFiles,
zipCheckFunctions,
zipFixture,
zipNode,
} from './helpers/main.js'
import { computeSha1 } from './helpers/sha.js'
import { allBundleConfigs, testMany } from './helpers/test_many.js'
// eslint-disable-next-line import/no-unassigned-import
import 'source-map-support/register'
vi.mock('../src/utils/shell.js', () => ({ shellUtils: { runCommand: vi.fn() } }))
const getZipChecksum = async function (opts: ZipFunctionsOptions) {
const {
files: [{ path }],
} = await zipFixture('many-dependencies', { opts, fixtureDir: opts.basePath })
return computeSha1(path)
}
interface CustomMatchers {
toPathExist(): Promise<void>
}
declare module 'vitest' {
// eslint-disable-next-line @typescript-eslint/no-empty-interface
interface Assertion extends CustomMatchers {}
// eslint-disable-next-line @typescript-eslint/no-empty-interface
interface AsymmetricMatchersContaining extends CustomMatchers {}
}
describe('zip-it-and-ship-it', () => {
afterEach(() => {
vi.resetAllMocks()
})
testMany('Zips Node.js function files', [...allBundleConfigs, 'bundler_none'], async (options) => {
const fixtureName = 'simple'
const { files } = await zipNode(fixtureName, { opts: options })
expect(files[0].invocationMode).toBeUndefined()
expect(files[0].runtime).toBe('js')
expect(files[0].mainFile).toBe(join(FIXTURES_DIR, fixtureName, 'function.js'))
})
testMany(
'Zips Node.js function files from an internal functions dir with a configured fields',
[...allBundleConfigs, 'bundler_none'],
async (options) => {
const fixtureName = join('node-internal', '.netlify/internal-functions')
const { files } = await zipFixture(fixtureName, {
length: 2,
opts: {
...options,
internalSrcFolder: join(FIXTURES_DIR, fixtureName),
config: { 'function-1': { name: 'Function One', generator: '@netlify/mock-plugin@1.0.0' } },
},
})
expect(files[0].displayName).toBe('Function One')
expect(files[0].generator).toBe('@netlify/mock-plugin@1.0.0')
expect(files[0].invocationMode).toBeUndefined()
expect(files[1].displayName).toBeUndefined()
expect(files[1].generator).toBe('internalFunc')
expect(files[1].invocationMode).toBeUndefined()
},
)
testMany(
'Handles Node module with native bindings (buildtime marker module)',
[...allBundleConfigs],
async (opts) => {
const bundler = getBundlerNameFromOptions(opts)
const fixtureDir = 'node-module-native-buildtime'
const { files } = await zipNode(fixtureDir, { opts })
const [{ runtime, unzipPath }] = files
const requires = await getRequires({ filePath: resolve(unzipPath, 'function.js') })
const normalizedRequires = new Set(requires.map((path) => unixify(path)))
expect(runtime).toBe('js')
const moduleWithNodeFile = resolve(FIXTURES_DIR, `${fixtureDir}/node_modules/module-with-node-file`)
await expect(`${unzipPath}/node_modules/module-with-node-file/native.node`).toPathExist()
await expect(`${unzipPath}/node_modules/module-with-node-file/side-file.js`).toPathExist()
expect(normalizedRequires.has('module-with-node-file')).toBe(true)
const moduleWithNodeGypPath = resolve(FIXTURES_DIR, `${fixtureDir}/node_modules/module-with-node-gyp`)
await expect(`${unzipPath}/node_modules/module-with-node-gyp/native.node`).toPathExist()
await expect(`${unzipPath}/node_modules/module-with-node-gyp/side-file.js`).toPathExist()
expect(normalizedRequires.has('module-with-node-gyp')).toBe(true)
const moduleWithPrebuildPath = resolve(FIXTURES_DIR, `${fixtureDir}/node_modules/module-with-prebuild`)
await expect(`${unzipPath}/node_modules/module-with-prebuild/native.node`).toPathExist()
await expect(`${unzipPath}/node_modules/module-with-prebuild/side-file.js`).toPathExist()
expect(normalizedRequires.has('module-with-prebuild')).toBe(true)
// We can only detect native modules when using esbuild.
if (bundler === NODE_BUNDLER.ESBUILD || bundler === NODE_BUNDLER.ESBUILD_ZISI) {
expect(files[0].nativeNodeModules).toEqual({
'module-with-node-file': { [moduleWithNodeFile]: '3.0.0' },
'module-with-node-gyp': { [moduleWithNodeGypPath]: '1.0.0' },
'module-with-prebuild': { [moduleWithPrebuildPath]: '2.0.0' },
})
}
},
)
testMany(
'Handles Node module with native bindings (runtime marker module)',
[...allBundleConfigs],
async (options) => {
const bundler = getBundlerNameFromOptions(options)
const fixtureDir = 'node-module-native-runtime'
const { files } = await zipNode(fixtureDir, {
opts: options,
})
const requires = await getRequires({ filePath: resolve(files[0].unzipPath, 'function.js') })
const normalizedRequires = new Set(requires.map((path) => unixify(path)))
const modulePath = resolve(FIXTURES_DIR, `${fixtureDir}/node_modules/test`)
const [{ runtime, unzipPath }] = files
expect(runtime).toBe('js')
await expect(`${unzipPath}/node_modules/test/native.node`).toPathExist()
await expect(`${unzipPath}/node_modules/test/side-file.js`).toPathExist()
expect(normalizedRequires.has('test')).toBe(true)
// We can only detect native modules when using esbuild.
if (bundler === NODE_BUNDLER.ESBUILD || bundler === NODE_BUNDLER.ESBUILD_ZISI) {
expect(files[0].nativeNodeModules).toEqual({ test: { [modulePath]: '1.0.0' } })
}
},
)
testMany('Can require node modules', [...allBundleConfigs], async (options) => {
await zipNode('local-node-module', { opts: options })
})
testMany('Can require deep paths in node modules', [...allBundleConfigs], async (options) => {
const { files } = await zipNode('local-node-module-deep-require', {
opts: options,
})
const func = await importFunctionFile(`${files[0].unzipPath}/function.js`)
expect(func).toEqual({ mock: { stack: 'jam' }, stack: 'jam' })
})
testMany('Can require Node modules with destructuring expressions', [...allBundleConfigs], async (options) => {
await zipNode(`local-node-module-destructure-require`, {
opts: options,
})
})
testMany('Can require scoped node modules', [...allBundleConfigs], async (options) => {
await zipNode('node-module-scope', { opts: options })
})
testMany('Can require node modules nested files', [...allBundleConfigs], async (options) => {
await zipNode('node-module-path', { opts: options })
})
testMany('Can require dynamically generated node modules', [...allBundleConfigs], async (options) => {
await zipNode('side-module', { opts: options })
})
describe('aws-sdk special case', () => {
testMany(
'On Node v18, includes v2 and excludes v3',
['bundler_default', 'bundler_esbuild', 'bundler_esbuild_zisi', 'bundler_default_nft', 'bundler_nft'],
async (options) => {
const fixtureName = 'node-module-excluded'
const opts = merge(options, {
basePath: join(FIXTURES_DIR, fixtureName),
config: {
'*': {
...options.config['*'],
nodeVersion: '18',
},
},
})
const { files } = await zipNode(fixtureName, { opts })
const [{ unzipPath, bundler, entryFilename }] = files
if (bundler === 'esbuild') {
// esbuild bundles everything into one file, so we need to assert on the file contents
const bundle = await readFile(`${unzipPath}/${entryFilename}`, 'utf-8')
expect(bundle).toContain('/aws-sdk')
expect(bundle).not.toContain('/@aws-sdk')
} else {
await expect(`${files[0].unzipPath}/node_modules/aws-sdk`).toPathExist()
await expect(`${files[0].unzipPath}/node_modules/@aws-sdk/client-s3`).not.toPathExist()
}
try {
const func = await importFunctionFile(`${files[0].unzipPath}/function.js`)
func()
expect.fail('Running the function should fail due to the missing module')
} catch (error) {
expect(error.code).toBe('MODULE_NOT_FOUND')
}
},
)
testMany(
'On Node v16, excludes v2 and includes v3',
['bundler_default', 'bundler_esbuild', 'bundler_esbuild_zisi', 'bundler_default_nft', 'bundler_nft'],
async (options) => {
const fixtureName = 'node-module-excluded'
const opts = merge(options, {
basePath: join(FIXTURES_DIR, fixtureName),
config: {
'*': {
...options.config['*'],
nodeVersion: '16',
},
},
})
const { files } = await zipNode(fixtureName, { opts })
const [{ unzipPath, bundler, entryFilename }] = files
if (bundler === 'esbuild') {
// esbuild bundles everything into one file, so we need to assert on the file contents
const bundle = await readFile(`${unzipPath}/${entryFilename}`, 'utf-8')
expect(bundle).not.toContain('/aws-sdk')
expect(bundle).toContain('/@aws-sdk')
} else {
await expect(`${files[0].unzipPath}/node_modules/aws-sdk`).not.toPathExist()
await expect(`${files[0].unzipPath}/node_modules/@aws-sdk/client-s3`).toPathExist()
}
try {
const func = await importFunctionFile(`${files[0].unzipPath}/function.js`)
func()
expect.fail('Running the function should fail due to the missing module')
} catch (error) {
expect(error.code).toBe('MODULE_NOT_FOUND')
}
},
)
})
testMany('Ignore TypeScript types', [...allBundleConfigs], async (options) => {
const { files } = await zipNode('node-module-typescript-types', {
opts: options,
})
await expect(`${files[0].unzipPath}/node_modules/@types/node`).not.toPathExist()
})
testMany('Throws on runtime errors', [...allBundleConfigs], async (options) => {
await expect(zipNode('node-module-error', { opts: options })).rejects.toThrowError()
})
testMany('Throws on missing dependencies', [...allBundleConfigs], async (options) => {
await expect(zipNode('node-module-missing', { opts: options })).rejects.toThrowError()
})
testMany('Throws on missing dependencies with no optionalDependencies', [...allBundleConfigs], async (options) => {
await expect(zipNode('node-module-missing-package', { opts: options })).rejects.toThrowError()
})
testMany('Throws on missing conditional dependencies', [...allBundleConfigs], async (options) => {
await expect(zipNode('node-module-missing-conditional', { opts: options })).rejects.toThrowError()
})
testMany("Throws on missing dependencies' dependencies", [...allBundleConfigs], async (options) => {
await expect(zipNode('node-module-missing-deep', { opts: options })).rejects.toThrowError()
})
testMany('Ignore missing optional dependencies', [...allBundleConfigs], async (options) => {
await zipNode('node-module-missing-optional', { opts: options })
})
testMany('Ignore modules conditional dependencies', [...allBundleConfigs], async (options) => {
await zipNode('node-module-deep-conditional', { opts: options })
})
testMany('Ignore missing optional peer dependencies', [...allBundleConfigs], async (options) => {
await zipNode('node-module-peer-optional', { opts: options })
})
testMany(
'Throws on missing optional peer dependencies with no peer dependencies',
[...allBundleConfigs],
async (options) => {
await expect(zipNode('node-module-peer-optional-none', { opts: options })).rejects.toThrowError()
},
)
testMany('Throws on missing non-optional peer dependencies', [...allBundleConfigs], async (options) => {
await expect(zipNode('node-module-peer-not-optional', { opts: options })).rejects.toThrowError()
})
testMany(
'Resolves dependencies from .netlify/plugins/node_modules when using `zipFunctions()`',
[...allBundleConfigs],
async (options) => {
await zipNode('node-module-next-image', { opts: options })
},
)
// We persist `package.json` as `package.json.txt` in git. Otherwise ESLint
// tries to load when linting sibling JavaScript files. In this test, we
// temporarily rename it to an actual `package.json`.
testMany(
'Throws on invalid package.json',
['bundler_default', 'bundler_esbuild', 'bundler_esbuild_zisi'],
async (options) => {
await expect(zipNode('invalid-package-json', { opts: options })).rejects.toThrowError(
/(invalid json|package.json:1:1: error: expected string in json but found "{")/i,
)
},
)
testMany('Ignore invalid require()', [...allBundleConfigs], async (options) => {
await zipNode('invalid-require', { opts: options })
})
testMany('Can use dynamic import() with esbuild', ['bundler_esbuild'], async (options) => {
await zipNode('dynamic-import', { opts: options })
})
testMany('Can require local files', [...allBundleConfigs], async (options) => {
await zipNode('local-require', { opts: options })
})
testMany(
'Can bundle ESM functions and transpile them to CJS when the Node version is <14 and `archiveType` is `none`',
['bundler_default', 'bundler_esbuild', 'bundler_nft'],
async (options) => {
const length = 4
const fixtureName = 'local-require-esm'
const opts = merge(options, {
archiveFormat: ARCHIVE_FORMAT.NONE,
basePath: join(FIXTURES_DIR, fixtureName),
config: {
'*': {
nodeVersion: 'nodejs12.x',
},
},
featureFlags: { zisi_pure_esm: false },
})
const { tmpDir } = await zipFixture(fixtureName, {
length,
opts,
})
const functionPaths = [
join(tmpDir, 'function', 'function.js'),
join(tmpDir, 'function_cjs', 'function_cjs.js'),
join(tmpDir, 'function_export_only', 'function_export_only.js'),
join(tmpDir, 'function_import_only', 'function_import_only.js'),
]
const func1 = () => importFunctionFile(functionPaths[0])
const func2 = () => importFunctionFile(functionPaths[1])
const func3 = () => importFunctionFile(functionPaths[2])
const func4 = () => importFunctionFile(functionPaths[3])
const functionsAreESM = await Promise.all(
functionPaths.map((functionPath) => detectEsModule({ mainFile: functionPath })),
)
// None of the functions should be ESM since we're transpiling them to CJS.
expect(functionsAreESM.some(Boolean)).toBe(false)
const func2Default = await func2()
expect(await func2Default()).toBe(0)
const { ZERO } = await func1()
expect(ZERO).toBe(0)
const { howdy } = await func3()
expect(howdy).toBeTypeOf('string')
expect(await func4()).toEqual({})
},
)
testMany(
'Can bundle CJS functions that import ESM files with an `import()` expression',
['bundler_default', 'bundler_esbuild', 'bundler_nft'],
async (opts) => {
const fixtureName = 'node-cjs-importing-mjs-extension'
const { files } = await zipFixture(fixtureName, {
opts,
})
const unzippedFunctions = await unzipFiles(files)
const func = await importFunctionFile(join(unzippedFunctions[0].unzipPath, 'function.js'))
const { body, statusCode } = await func.handler()
expect(body).toBe('Hello world')
expect(statusCode).toBe(200)
},
)
testMany(
'Can bundle native ESM functions when the Node version is >=14 and the `zisi_pure_esm` flag is on',
['bundler_default', 'bundler_nft', 'bundler_esbuild'],
async (options) => {
const length = 2
const fixtureName = 'node-esm'
const opts = merge(options, {
basePath: join(FIXTURES_DIR, fixtureName),
featureFlags: { zisi_pure_esm: true },
})
const { files } = await zipFixture(fixtureName, {
length,
opts,
})
const unzippedFunctions = await unzipFiles(files)
const functionPaths = [
join(unzippedFunctions[0].unzipPath, 'func1.js'),
join(unzippedFunctions[1].unzipPath, 'func2.js'),
]
const func1 = await importFunctionFile(functionPaths[0])
const func2 = await importFunctionFile(functionPaths[1])
expect(func1.handler()).toBe(true)
expect(func2.handler()).toBe(true)
const functionsAreESM = await Promise.all(
functionPaths.map((functionPath) => detectEsModule({ mainFile: functionPath })),
)
expect(functionsAreESM.every(Boolean)).toBe(true)
},
)
testMany(
'Can bundle ESM functions and transpile them to CJS when the Node version is >=14 and the `zisi_pure_esm` flag is off',
['bundler_default', 'bundler_esbuild', 'bundler_nft'],
async (options) => {
const length = 2
const fixtureName = 'node-esm'
const opts = merge(options, {
basePath: join(FIXTURES_DIR, fixtureName),
})
const { files } = await zipFixture(fixtureName, {
length,
opts,
})
const unzippedFunctions = await unzipFiles(files)
const functionPaths = [
join(unzippedFunctions[0].unzipPath, 'func1.js'),
join(unzippedFunctions[1].unzipPath, 'func2.js'),
]
const func1 = await importFunctionFile(functionPaths[0])
const func2 = await importFunctionFile(functionPaths[1])
expect(func1.handler()).toBe(true)
expect(func2.handler()).toBe(true)
const functionsAreESM = await Promise.all(
functionPaths.map((functionPath) => detectEsModule({ mainFile: functionPath })),
)
expect(functionsAreESM.some(Boolean)).toBe(false)
},
)
testMany('Can require local files deeply', [...allBundleConfigs], async (options) => {
await zipNode('local-deep-require', { opts: options })
})
testMany('Can require local files in the parent directories', [...allBundleConfigs], async (options) => {
await zipNode('local-parent-require', { opts: options })
})
testMany('Ignore missing critters dependency for Next.js 10', [...allBundleConfigs], async (options) => {
await zipNode('node-module-next10-critters', { opts: options })
})
testMany(
'Ignore missing critters dependency for Next.js exact version 10.0.5',
[...allBundleConfigs],
async (options) => {
await zipNode('node-module-next10-critters-exact', { opts: options })
},
)
testMany(
'Ignore missing critters dependency for Next.js with range ^10.0.5',
[...allBundleConfigs],
async (options) => {
await zipNode('node-module-next10-critters-10.0.5-range', {
opts: options,
})
},
)
testMany(
"Ignore missing critters dependency for Next.js with version='latest'",
[...allBundleConfigs],
async (options) => {
await zipNode('node-module-next10-critters-latest', { opts: options })
},
)
// Need to create symlinks dynamically because they sometimes get lost when
// committed on Windows
if (platform !== 'win32') {
testMany('Can require symlinks', [...allBundleConfigs], async (options) => {
const fixtureTmpDir = await tmpName({ prefix: 'zip-it-test' })
const opts = merge(options, {
basePath: `${fixtureTmpDir}/symlinks`,
})
await cpy('symlinks/**', `${fixtureTmpDir}/symlinks`, {
cwd: FIXTURES_DIR,
})
const symlinkDir = `${fixtureTmpDir}/symlinks/function`
const symlinkFile = `${symlinkDir}/file.js`
const targetFile = `${symlinkDir}/target.js`
if (!(await pathExists(symlinkFile))) {
await symlink(targetFile, symlinkFile)
}
try {
await zipNode('symlinks', { opts, fixtureDir: fixtureTmpDir })
} finally {
await rm(symlinkFile, { force: true, maxRetries: 10 })
}
})
}
testMany('Can target a directory with a main file with the same name', [...allBundleConfigs], async (options) => {
const fixtureName = 'directory-handler'
const { files } = await zipNode(fixtureName, { opts: options })
expect(files[0].mainFile).toBe(join(FIXTURES_DIR, fixtureName, 'function', 'function.js'))
})
testMany(
'Includes side files when the function is in a subdirectory',
[...allBundleConfigs],
async (options, variant) => {
const shouldIncludeFiles = variant === 'bundler_default' || variant === 'bundler_default_nft'
const { files } = await zipFixture('directory-side-files', { length: 2, opts: options })
const unzippedFunctions = await unzipFiles(files)
const [funcV1, funcV2] = unzippedFunctions
const expectedBundler = {
bundler_default: 'zisi',
bundler_esbuild: 'esbuild',
bundler_esbuild_zisi: 'esbuild',
bundler_default_nft: 'nft',
bundler_nft: 'nft',
}
expect(funcV1.bundler).toBe(expectedBundler[variant])
expect(funcV1.runtimeAPIVersion).toBe(1)
if (shouldIncludeFiles) {
await expect(`${funcV1.unzipPath}/robots.txt`).toPathExist()
await expect(`${funcV1.unzipPath}/sub-dir/sub-file.js`).toPathExist()
} else {
await expect(`${funcV1.unzipPath}/robots.txt`).not.toPathExist()
await expect(`${funcV1.unzipPath}/sub-dir/sub-file.js`).not.toPathExist()
}
await expect(`${funcV1.unzipPath}/Desktop.ini`).not.toPathExist()
await expect(`${funcV1.unzipPath}/node_modules`).not.toPathExist()
expect(funcV2.bundler).toBe('nft')
expect(funcV2.runtimeAPIVersion).toBe(2)
await expect(`${funcV2.unzipPath}/robots.txt`).not.toPathExist()
await expect(`${funcV2.unzipPath}/Desktop.ini`).not.toPathExist()
await expect(`${funcV2.unzipPath}/node_modules`).not.toPathExist()
},
)
testMany('Can target a directory with an index.js file', [...allBundleConfigs], async (options) => {
const fixtureName = 'index-handler'
const { files } = await zipFixture(fixtureName, {
opts: options,
})
const unzippedFunctions = await unzipFiles(files)
const returnValue = await importFunctionFile(`${unzippedFunctions[0].unzipPath}/function.js`)
expect(returnValue).toBe(true)
expect(files[0].mainFile).toBe(join(FIXTURES_DIR, fixtureName, 'function', 'index.js'))
})
testMany('Keeps non-required files inside the target directory', [...allBundleConfigs], async (options) => {
const { files } = await zipNode('keep-dir-files', { opts: options })
await expect(`${files[0].unzipPath}/function.js`).toPathExist()
})
testMany('Ignores non-required node_modules inside the target directory', [...allBundleConfigs], async (options) => {
const { files } = await zipNode('ignore-dir-node-modules', {
opts: options,
})
await expect(`${files[0].unzipPath}/node_modules`).not.toPathExist()
})
testMany(
'Ignores deep non-required node_modules inside the target directory',
[...allBundleConfigs],
async (options) => {
const { files } = await zipNode('ignore-deep-dir-node-modules', {
opts: options,
})
await expect(`${files[0].unzipPath}/deep/node_modules`).not.toPathExist()
},
)
describe('many-dependencies fixture', () => {
let fixtureTmpDir: string
beforeAll(async () => {
fixtureTmpDir = await tmpName({ prefix: 'many-dependencies' })
const basePath = `${fixtureTmpDir}/many-dependencies`
await cpy('many-dependencies/**', basePath, { cwd: FIXTURES_DIR })
await execa('npm', ['install', '--no-package-lock', '--no-audit', '--prefer-offline', '--progress=false'], {
cwd: basePath,
})
}, 30_000)
afterAll(async () => {
// No need to cleanup on CI
if (isCI) return
await rm(fixtureTmpDir, { recursive: true, force: true, maxRetries: 10 })
})
testMany('Works with many dependencies', [...allBundleConfigs], async (options) => {
const opts = merge(options, {
basePath: fixtureTmpDir,
})
await zipNode('many-dependencies', { opts, fixtureDir: fixtureTmpDir })
})
testMany('Produces deterministic checksums', [...allBundleConfigs, 'bundler_none'], async (options) => {
const opts = merge(options, {
basePath: fixtureTmpDir,
})
const [checksumOne, checksumTwo] = await Promise.all([getZipChecksum(opts), getZipChecksum(opts)])
expect(checksumOne).toBe(checksumTwo)
})
})
testMany('Works with many function files', [...allBundleConfigs, 'bundler_none'], async (options) => {
const names = new Set(['one', 'two', 'three', 'four', 'five', 'six'])
const { files } = await zipNode('many-functions', {
opts: options,
length: 6,
})
files.forEach(({ name }) => {
expect(names.has(name)).toBe(true)
})
})
testMany('Throws when the source folder does not exist', [...allBundleConfigs, 'bundler_none'], async (options) => {
await expect(zipNode('does-not-exist', { opts: options })).rejects.toThrowError(/Functions folders do not exist/)
})
testMany(
'Works even if destination folder does not exist',
[...allBundleConfigs, 'bundler_none'],
async (options) => {
await zipNode('simple', { opts: options })
},
)
testMany(
'Do not consider node_modules as a function file',
[...allBundleConfigs, 'bundler_none'],
async (options) => {
await zipNode('ignore-node-modules', { opts: options })
},
)
testMany('Ignore directories without a main file', [...allBundleConfigs, 'bundler_none'], async (options) => {
await zipNode('ignore-directories', { opts: options })
})
testMany('Remove useless files', [...allBundleConfigs], async (options) => {
const { files } = await zipNode('useless', { opts: options })
await expect(`${files[0].unzipPath}/Desktop.ini`).not.toPathExist()
})
testMany('Works on empty directories', [...allBundleConfigs, 'bundler_none'], async (options) => {
await zipNode('empty', { opts: options, length: 0 })
})
testMany('Works when no package.json is present', [...allBundleConfigs], async (options) => {
const fixtureDir = await tmpName({ prefix: 'zip-it-test' })
const opts = merge(options, {
basePath: fixtureDir,
})
await cpy('no-package-json/**', `${fixtureDir}/no-package-json`, {
cwd: FIXTURES_DIR,
})
await zipNode('no-package-json', { opts, fixtureDir })
})
testMany('Copies already zipped files', [...allBundleConfigs, 'bundler_none'], async () => {
const tmpDir = await tmpName({ prefix: 'zip-it-test' })
const { files } = await zipCheckFunctions('keep-zip', { tmpDir })
expect(files[0].runtime).toBe('js')
const fileContents = await readFile(files[0].path, 'utf8')
expect(fileContents.trim()).toBe('test')
})
testMany('Ignore unsupported programming languages', [...allBundleConfigs, 'bundler_none'], async (options) => {
await zipFixture('unsupported', { length: 0, opts: options })
})
testMany('Can reduce parallelism', [...allBundleConfigs, 'bundler_none'], async (options) => {
const opts = merge(options, { parallelLimit: 1 })
await zipNode('simple', { opts })
})
testMany('Zips node modules', ['bundler_default', 'bundler_nft'], async (options) => {
await zipNode('node-module', { opts: options })
})
testMany('Include most files from node modules', ['bundler_default'], async (options) => {
const fixtureName = 'node-module-included'
const opts = merge(options, {
basePath: join(FIXTURES_DIR, fixtureName),
})
const { files } = await zipNode('node-module-included', { opts })
await expect(`${files[0].unzipPath}/node_modules/test/test.map`).not.toPathExist()
await expect(`${files[0].unzipPath}/node_modules/test/test.html`).toPathExist()
})
testMany('Throws on missing critters dependency for Next.js 9', ['bundler_default'], async (options) => {
await expect(zipNode('node-module-next9-critters', { opts: options })).rejects.toThrowError()
})
testMany(
'Includes specific Next.js dependencies when using next-on-netlify',
['bundler_default'],
async (options) => {
const { files } = await zipNode('node-module-next-on-netlify', {
opts: options,
})
await expect(`${files[0].unzipPath}/node_modules/next/dist/next-server/lib/constants.js`).toPathExist()
await expect(`${files[0].unzipPath}/node_modules/next/dist/compiled/semver.js`).toPathExist()
await expect(`${files[0].unzipPath}/node_modules/next/dist/other.js`).not.toPathExist()
await expect(`${files[0].unzipPath}/node_modules/next/index.js`).not.toPathExist()
},
)
testMany('Includes all Next.js dependencies when not using next-on-netlify', ['bundler_default'], async (options) => {
const { files } = await zipNode('node-module-next', { opts: options })
await expect(`${files[0].unzipPath}/node_modules/next/dist/next-server/lib/constants.js`).toPathExist()
await expect(`${files[0].unzipPath}/node_modules/next/dist/compiled/semver.js`).toPathExist()
await expect(`${files[0].unzipPath}/node_modules/next/dist/other.js`).toPathExist()
await expect(`${files[0].unzipPath}/node_modules/next/index.js`).toPathExist()
})
testMany('Inlines node modules in the bundle', ['bundler_esbuild'], async (options) => {
const { files } = await zipNode('node-module-included-try-catch', {
opts: options,
})
const requires = await getRequires({ filePath: resolve(files[0].unzipPath, 'function.js') })
expect(requires.includes('test')).toBe(false)
await expect(`${files[0].unzipPath}/node_modules/test`).not.toPathExist()
})
testMany(
'Does not inline node modules and includes them in a `node_modules` directory if they are defined in `externalNodeModules`',
['bundler_esbuild'],
async (options) => {
const opts = merge(options, {
config: {
function: {
externalNodeModules: ['test'],
},
},
})
const { files } = await zipNode('node-module-included-try-catch', {
opts,
})
const requires = await getRequires({ filePath: resolve(files[0].unzipPath, 'function.js') })
expect(requires.includes('test')).toBe(true)
await expect(`${files[0].unzipPath}/node_modules/test`).toPathExist()
},
)
testMany(
'Does not inline node modules and excludes them from the bundle if they are defined in `ignoredNodeModules`',
['bundler_esbuild'],
async (options) => {
const opts = merge(options, {
config: {
function: {
ignoredNodeModules: ['test'],
},
},
})
const { files } = await zipNode('node-module-included-try-catch', {
opts,
})
const requires = await getRequires({ filePath: resolve(files[0].unzipPath, 'function.js') })
expect(requires.includes('test')).toBe(true)
await expect(`${files[0].unzipPath}/function/node_modules/test`).not.toPathExist()
},
)
testMany(
'Include most files from node modules present in `externalNodeModules`',
['bundler_esbuild'],
async (options) => {
const opts = merge(options, {
config: {
function: {
externalNodeModules: ['test'],
},
},
})
const { files } = await zipNode('node-module-included', {
opts,
})
expect(`${files[0].unzipPath}/node_modules/test/test.map`).not.toPathExist()
expect(`${files[0].unzipPath}/node_modules/test/test.html`).toPathExist()
},
)
testMany(
'Does not throw if one of the modules defined in `externalNodeModules` does not exist',
['bundler_esbuild'],
async (options) => {
const opts = merge(options, {
config: {
function: {
externalNodeModules: ['i-do-not-exist'],
},
},
})
const { files } = await zipNode('node-module-included-try-catch', {
opts,
})
await expect(`${files[0].unzipPath}/node_modules/i-do-not-exist`).not.toPathExist()
},
)
testMany(
'Exposes the main export of `node-fetch` when imported using `require()`',
[...allBundleConfigs],
async (options) => {
const { files } = await zipFixture('node-fetch', { opts: options })
const unzippedFunctions = await unzipFiles(files)
const returnValue = await importFunctionFile(`${unzippedFunctions[0].unzipPath}/function.js`)
expect(returnValue).toBeTypeOf('function')
},
)
testMany(
'{name}/{name}.js takes precedence over {name}.js and {name}/index.js',
[...allBundleConfigs, 'bundler_none'],
async (options) => {
const { files } = await zipFixture('conflicting-names-1', {
opts: options,
})
const unzippedFunctions = await unzipFiles(files)
const returnValue = await importFunctionFile(`${unzippedFunctions[0].unzipPath}/function.js`)
expect(returnValue).toBe('function-js-file-in-directory')
},
)
testMany(
'{name}/index.js takes precedence over {name}.js',
[...allBundleConfigs, 'bundler_none'],
async (options) => {
const { files } = await zipFixture('conflicting-names-2', {
opts: options,
})
const unzippedFunctions = await unzipFiles(files)
const returnValue = await importFunctionFile(`${unzippedFunctions[0].unzipPath}/function.js`)
expect(returnValue).toBe('index-js-file-in-directory')
},
)
testMany(
'{name}/index.js takes precedence over {name}/index.ts',
[...allBundleConfigs, 'bundler_none'],
async (options) => {
const { files } = await zipFixture('conflicting-names-3', {
opts: options,
})
const unzippedFunctions = await unzipFiles(files)
const { type } = await importFunctionFile(`${unzippedFunctions[0].unzipPath}/function.js`)
expect(type).toBe('index-js-file-in-directory')
},
)
testMany('{name}.js takes precedence over {name}.ts', [...allBundleConfigs, 'bundler_none'], async (options) => {
const { files } = await zipFixture('conflicting-names-4', {
opts: options,
})
const unzippedFunctions = await unzipFiles(files)
const { type } = await importFunctionFile(`${unzippedFunctions[0].unzipPath}/function.js`)
expect(type).toBe('function-js-file')
})
testMany('{name}.js takes precedence over {name}.zip', [...allBundleConfigs, 'bundler_none'], async (options) => {
const { files } = await zipFixture('conflicting-names-5', {
opts: options,
})
const unzippedFunctions = await unzipFiles(files)
const { type } = await importFunctionFile(`${unzippedFunctions[0].unzipPath}/function.js`)
expect(type).toBe('function-js-file')
})
testMany(
'Handles a TypeScript function ({name}.ts)',
['bundler_default', 'bundler_esbuild', 'bundler_esbuild_zisi', 'bundler_default_nft', 'bundler_nft'],
async (options) => {
const { files } = await zipFixture('node-typescript', {
opts: options,
})
const unzippedFunctions = await unzipFiles(files)
const { handler } = await importFunctionFile(`${unzippedFunctions[0].unzipPath}/function.js`)
expect(handler()).toBe('❤️ TypeScript')
},
)
testMany(
'Handles a TypeScript function ({name}/{name}.ts)',
['bundler_default', 'bundler_esbuild', 'bundler_esbuild_zisi', 'bundler_default_nft', 'bundler_nft'],
async (options) => {
const { files } = await zipFixture('node-typescript-directory-1', {
opts: options,
})
const unzippedFunctions = await unzipFiles(files)
const { handler } = await importFunctionFile(`${unzippedFunctions[0].unzipPath}/function.js`)
expect(handler()).toBe('❤️ TypeScript')
},
)
testMany(
'Handles a TypeScript function ({name}/index.ts)',
['bundler_default', 'bundler_esbuild', 'bundler_esbuild_zisi', 'bundler_default_nft', 'bundler_nft'],
async (options) => {
const { files } = await zipFixture('node-typescript-directory-2', {
opts: options,
})