Skip to content
File

Blob: src/workerd/api/tests/importable-exports-test.js

javascript88 lines
1// Copyright (c) 2025 Cloudflare, Inc.
2// Licensed under the Apache 2.0 license found in the LICENSE file or at:
3// https://opensource.org/licenses/Apache-2.0
4import { strictEqual, ok, deepStrictEqual } from 'node:assert';
5import { DurableObject, exports, withExports } from 'cloudflare:workers';
6 
7export class MyService extends DurableObject {
8 greet(name) {
9 return `Hello, ${name}!`;
10 }
11}
12 
13export const importableExports = {
14 async test() {
15 ok(
16 exports.importableExports,
17 'exports.importableExports should be defined'
18 );
19 ok(exports.nullableExports, 'exports.nullableExports should be defined');
20 ok(exports.MyService, 'exports.MyService should be defined');
21 
22 const keys = Object.keys(exports).sort();
23 deepStrictEqual(keys, [
24 'MyService',
25 'importableExports',
26 'nullableExports',
27 ]);
28 
29 const id = exports.MyService.idFromName('test');
30 const stub = exports.MyService.get(id);
31 strictEqual(await stub.greet('World'), 'Hello, World!');
32 
33 await scheduler.wait(10);
34 ok(
35 exports.importableExports,
36 'exports.importableExports should persist after async wait'
37 );
38 
39 const customExports = { customValue: 'test', customNumber: 42 };
40 const result = await withExports(customExports, async () => {
41 await scheduler.wait(10);
42 strictEqual(exports.customValue, 'test');
43 strictEqual(exports.customNumber, 42);
44 strictEqual(
45 exports.importableExports,
46 undefined,
47 'base exports should be masked'
48 );
49 return exports.customValue;
50 });
51 strictEqual(result, 'test');
52 
53 ok(
54 exports.importableExports,
55 'exports should be restored after withExports'
56 );
57 strictEqual(exports.customValue, undefined);
58 
59 for (const value of ['string', 123]) {
60 await withExports(value, async () => {
61 await scheduler.wait(10);
62 ok(
63 exports.importableExports,
64 'non-object values should fall back to base exports'
65 );
66 });
67 }
68 },
69};
70 
71export const nullableExports = {
72 async test() {
73 await withExports(null, async () => {
74 strictEqual(exports.importableExports, undefined);
75 strictEqual(exports.nullableExports, undefined);
76 strictEqual(typeof exports, 'object');
77 });
78 
79 await withExports(undefined, async () => {
80 strictEqual(exports.importableExports, undefined);
81 strictEqual(exports.nullableExports, undefined);
82 strictEqual(typeof exports, 'object');
83 });
84 
85 ok(exports.importableExports, 'exports should be restored');
86 },
87};