@cyc-seattle/gsuite-sdk 0.1.1 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +65 -0
- package/dist/common.d.ts +8 -1
- package/dist/common.js +4 -4
- package/dist/directory.d.ts +14 -2
- package/dist/directory.js +25 -13
- package/dist/fake/clock.d.ts +12 -0
- package/dist/fake/clock.js +14 -0
- package/dist/fake/errors.d.ts +22 -0
- package/dist/fake/errors.js +27 -0
- package/dist/fake/index.d.ts +4 -0
- package/dist/fake/index.js +4 -0
- package/dist/fake/model.d.ts +96 -0
- package/dist/fake/model.js +312 -0
- package/dist/fake/server.d.ts +18 -0
- package/dist/fake/server.js +165 -0
- package/package.json +9 -3
package/README.md
CHANGED
|
@@ -49,6 +49,17 @@ const members = await new DirectoryClient(auth).listMembers("team@example.org");
|
|
|
49
49
|
const settings = await new GroupSettingsClient(auth).getSettings("team@example.org");
|
|
50
50
|
```
|
|
51
51
|
|
|
52
|
+
### Client options
|
|
53
|
+
|
|
54
|
+
`DirectoryClient` and `GroupSettingsClient` take an optional second argument:
|
|
55
|
+
|
|
56
|
+
- `rootUrl` sends requests somewhere other than Google, such as the [Workspace fake](#workspace-fake). googleapis uses only its origin.
|
|
57
|
+
- `pacing` sets `safeCall`'s waits: `requestDelayMs` before every request (default 500) and `retryDelayMs` before the retry of a transient error (default 60000).
|
|
58
|
+
|
|
59
|
+
```ts
|
|
60
|
+
const directory = new DirectoryClient(auth, { rootUrl, pacing: { requestDelayMs: 0, retryDelayMs: 0 } });
|
|
61
|
+
```
|
|
62
|
+
|
|
52
63
|
## Retries
|
|
53
64
|
|
|
54
65
|
`safeCall` wraps a request. It waits between requests and retries transient errors, such as rate limits and 5xx responses.
|
|
@@ -59,6 +70,60 @@ import { safeCall } from "@cyc-seattle/gsuite-sdk";
|
|
|
59
70
|
await safeCall(() => row.save());
|
|
60
71
|
```
|
|
61
72
|
|
|
73
|
+
`safeCall(request, pacing)` takes the same `pacing` as the clients.
|
|
74
|
+
|
|
75
|
+
## Workspace fake
|
|
76
|
+
|
|
77
|
+
`@cyc-seattle/gsuite-sdk/fake` stands in for the Directory and Groups Settings APIs. It serves the calls that `DirectoryClient` and `GroupSettingsClient` make, from memory.
|
|
78
|
+
|
|
79
|
+
```ts
|
|
80
|
+
import { ManualClock, WorkspaceModel, startFakeServer } from "@cyc-seattle/gsuite-sdk/fake";
|
|
81
|
+
|
|
82
|
+
const clock = new ManualClock();
|
|
83
|
+
const fake = await startFakeServer({ model: new WorkspaceModel({ clock }) });
|
|
84
|
+
const directory = new DirectoryClient(auth, { rootUrl: fake.rootUrl, pacing: { requestDelayMs: 0, retryDelayMs: 0 } });
|
|
85
|
+
// ...
|
|
86
|
+
await fake.close();
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
`startFakeServer` listens on a free loopback port unless given `host` and `port`. The clients still need an auth object, but the fake ignores its token. A `GoogleAuth` whose `authClient` is a `UserRefreshClient` holding any access token needs no ADC. `test/features/world.ts` builds one.
|
|
90
|
+
|
|
91
|
+
`WorkspaceModel` holds the groups, members, and settings. Use it directly in unit tests, or seed it before a test: pass `{ settled: true }` to `insertGroup` or `insertMember` to skip the new-group delay. Its options:
|
|
92
|
+
|
|
93
|
+
| Option | Default | What it does |
|
|
94
|
+
| ----------------- | ---------- | --------------------------------------------------------------------- |
|
|
95
|
+
| `clock` | the system | Where the model reads the time. `ManualClock` moves on `advance(ms)`. |
|
|
96
|
+
| `newGroupDelayMs` | 60000 | How long a new group refuses member inserts |
|
|
97
|
+
| `pageSize` | 200 | The largest page a list returns |
|
|
98
|
+
|
|
99
|
+
It answers as Google does:
|
|
100
|
+
|
|
101
|
+
| Case | Status | Reason | Message |
|
|
102
|
+
| ------------------------------------------ | ------ | ----------------- | -------------------------------- |
|
|
103
|
+
| An unknown group | 404 | `notFound` | `Resource Not Found: groupKey` |
|
|
104
|
+
| An unknown member | 404 | `notFound` | `Resource Not Found: memberKey` |
|
|
105
|
+
| A member insert into a group still too new | 404 | `notFound` | `Resource Not Found: groupKey` |
|
|
106
|
+
| A member who's already in the group | 409 | `duplicate` | `Member already exists.` |
|
|
107
|
+
| A group that already exists | 409 | `duplicate` | `Entity already exists.` |
|
|
108
|
+
| A membership that would make a cycle | 412 | `conditionNotMet` | `Cyclic memberships not allowed` |
|
|
109
|
+
| Settings of an unknown group | 404 | `notFound` | `Not Found` |
|
|
110
|
+
|
|
111
|
+
Google doesn't document the cycle's status or the settings 404's message. The fake follows the JSON API's conventions for them.
|
|
112
|
+
|
|
113
|
+
Derived membership isn't modeled, because the SDK reads only direct members.
|
|
114
|
+
|
|
115
|
+
Groups Settings answers in Atom XML unless the request asks for `alt=json`, like Google.
|
|
116
|
+
|
|
117
|
+
The `Dockerfile` runs the fake on port 8080, for a dev environment. `PORT` and `NEW_GROUP_DELAY_MS` override its defaults.
|
|
118
|
+
|
|
119
|
+
```sh
|
|
120
|
+
docker build -t gsuite-fake . && docker run -p 8080:8080 gsuite-fake
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
## Development
|
|
124
|
+
|
|
125
|
+
`mise run test` runs the unit tests in `test/`. `mise run integration` runs the Gherkin features in `features/` against the fake, which starts in the test process. `mise run ci` runs both, after `check`. See `AGENTS.md`.
|
|
126
|
+
|
|
62
127
|
## Release
|
|
63
128
|
|
|
64
129
|
Every merge to `main` releases from the PR title. The title must be a conventional commit. `fix:` makes a patch release, `feat:` a minor release, and a `!` after the type a major release. Types such as `docs:`, `build:`, and `test:` release nothing. semantic-release publishes to npm and creates the GitHub release.
|
package/dist/common.d.ts
CHANGED
|
@@ -25,10 +25,17 @@ export declare function getHttpStatus(error: unknown): number | undefined;
|
|
|
25
25
|
* transient and retried, since those are frequently recoverable.
|
|
26
26
|
*/
|
|
27
27
|
export declare function isRetryableError(error: unknown): boolean;
|
|
28
|
+
/** How `safeCall` spaces out requests. The defaults suit the real APIs; a fake can set both to 0. */
|
|
29
|
+
export interface Pacing {
|
|
30
|
+
/** Wait before every request. */
|
|
31
|
+
requestDelayMs?: number;
|
|
32
|
+
/** Wait before the retry of a transient failure, before jitter. */
|
|
33
|
+
retryDelayMs?: number;
|
|
34
|
+
}
|
|
28
35
|
/**
|
|
29
36
|
* Rate-limited wrapper for Google API calls with exponential backoff retry.
|
|
30
37
|
*
|
|
31
38
|
* Retries only transient failures (see {@link isRetryableError}); non-retryable
|
|
32
39
|
* errors are re-thrown immediately rather than incurring the backoff delay.
|
|
33
40
|
*/
|
|
34
|
-
export declare function safeCall<T>(request: () => Promise<T
|
|
41
|
+
export declare function safeCall<T>(request: () => Promise<T>, pacing?: Pacing): Promise<T>;
|
package/dist/common.js
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import winston from "winston";
|
|
2
2
|
import { backOff } from "exponential-backoff";
|
|
3
|
-
import { setTimeout } from "timers/promises";
|
|
4
3
|
// The default quota on Google Spreadsheet API is 60 requests/minute/user.
|
|
5
4
|
// However, there's a separate read and write quota, so we can safely double
|
|
6
5
|
// this to get a little bit more throughput.
|
|
@@ -66,12 +65,13 @@ export function isRetryableError(error) {
|
|
|
66
65
|
* Retries only transient failures (see {@link isRetryableError}); non-retryable
|
|
67
66
|
* errors are re-thrown immediately rather than incurring the backoff delay.
|
|
68
67
|
*/
|
|
69
|
-
export async function safeCall(request) {
|
|
70
|
-
|
|
68
|
+
export async function safeCall(request, pacing = {}) {
|
|
69
|
+
// The global timer, not timers/promises, so tests' fake timers control it.
|
|
70
|
+
await new Promise((resolve) => setTimeout(resolve, pacing.requestDelayMs ?? millisPerRequest));
|
|
71
71
|
return backOff(request, {
|
|
72
72
|
jitter: "full",
|
|
73
73
|
numOfAttempts: 2,
|
|
74
|
-
startingDelay: 60_000,
|
|
74
|
+
startingDelay: pacing.retryDelayMs ?? 60_000,
|
|
75
75
|
retry: (error) => {
|
|
76
76
|
if (!isRetryableError(error)) {
|
|
77
77
|
return false;
|
package/dist/directory.d.ts
CHANGED
|
@@ -1,4 +1,14 @@
|
|
|
1
1
|
import { Auth, groupssettings_v1 } from "googleapis";
|
|
2
|
+
import { type Pacing } from "./common.js";
|
|
3
|
+
/** Options for a Google API client. Omit them to call Google itself, at the default pace. */
|
|
4
|
+
export interface ClientOptions {
|
|
5
|
+
/**
|
|
6
|
+
* Where to send requests instead of Google, such as a Workspace fake. googleapis keeps only the
|
|
7
|
+
* origin: a path here is dropped.
|
|
8
|
+
*/
|
|
9
|
+
rootUrl?: string;
|
|
10
|
+
pacing?: Pacing;
|
|
11
|
+
}
|
|
2
12
|
export type GroupRole = "MEMBER" | "MANAGER" | "OWNER";
|
|
3
13
|
export interface Group {
|
|
4
14
|
id: string;
|
|
@@ -27,7 +37,8 @@ export type AddMemberResult = "added" | "already-member";
|
|
|
27
37
|
*/
|
|
28
38
|
export declare class DirectoryClient {
|
|
29
39
|
private client;
|
|
30
|
-
|
|
40
|
+
private pacing;
|
|
41
|
+
constructor(auth: Auth.GoogleAuth, options?: ClientOptions);
|
|
31
42
|
/**
|
|
32
43
|
* Gets a group by email or ID. Returns null if the group doesn't exist.
|
|
33
44
|
*/
|
|
@@ -72,7 +83,8 @@ export type GroupSettings = groupssettings_v1.Schema$Groups;
|
|
|
72
83
|
*/
|
|
73
84
|
export declare class GroupSettingsClient {
|
|
74
85
|
private client;
|
|
75
|
-
|
|
86
|
+
private pacing;
|
|
87
|
+
constructor(auth: Auth.GoogleAuth, options?: ClientOptions);
|
|
76
88
|
/**
|
|
77
89
|
* Gets a group's settings.
|
|
78
90
|
*/
|
package/dist/directory.js
CHANGED
|
@@ -11,11 +11,17 @@ const GROUP_ROLE_RANK = { MEMBER: 0, MANAGER: 1, OWNER: 2 };
|
|
|
11
11
|
*/
|
|
12
12
|
export class DirectoryClient {
|
|
13
13
|
client;
|
|
14
|
-
|
|
14
|
+
pacing;
|
|
15
|
+
constructor(auth, options = {}) {
|
|
16
|
+
this.pacing = options.pacing ?? {};
|
|
15
17
|
// The `directory_v1` cast is needed because `google.admin` also has overloads for
|
|
16
18
|
// two other API versions, which the `auth` cast below (needed for its own reasons —
|
|
17
19
|
// see CalendarClient) leaves TypeScript unable to discriminate between.
|
|
18
|
-
this.client = google.admin({
|
|
20
|
+
this.client = google.admin({
|
|
21
|
+
version: "directory_v1",
|
|
22
|
+
auth,
|
|
23
|
+
rootUrl: options.rootUrl,
|
|
24
|
+
});
|
|
19
25
|
}
|
|
20
26
|
/**
|
|
21
27
|
* Gets a group by email or ID. Returns null if the group doesn't exist.
|
|
@@ -29,7 +35,7 @@ export class DirectoryClient {
|
|
|
29
35
|
const group = await safeCall(async () => {
|
|
30
36
|
const response = await this.client.groups.get({ groupKey });
|
|
31
37
|
return response.data;
|
|
32
|
-
});
|
|
38
|
+
}, this.pacing);
|
|
33
39
|
return convertToGroup(group);
|
|
34
40
|
}
|
|
35
41
|
catch (error) {
|
|
@@ -58,7 +64,7 @@ export class DirectoryClient {
|
|
|
58
64
|
const page = await safeCall(async () => {
|
|
59
65
|
const response = await this.client.groups.list(params);
|
|
60
66
|
return response.data;
|
|
61
|
-
});
|
|
67
|
+
}, this.pacing);
|
|
62
68
|
groups.push(...(page.groups ?? []).map(convertToGroup));
|
|
63
69
|
pageToken = page.nextPageToken ?? undefined;
|
|
64
70
|
} while (pageToken);
|
|
@@ -82,7 +88,7 @@ export class DirectoryClient {
|
|
|
82
88
|
const group = await safeCall(async () => {
|
|
83
89
|
const response = await this.client.groups.insert({ requestBody });
|
|
84
90
|
return response.data;
|
|
85
|
-
});
|
|
91
|
+
}, this.pacing);
|
|
86
92
|
winston.info("Created group", { email: group.email });
|
|
87
93
|
return convertToGroup(group);
|
|
88
94
|
}
|
|
@@ -101,7 +107,7 @@ export class DirectoryClient {
|
|
|
101
107
|
const page = await safeCall(async () => {
|
|
102
108
|
const response = await this.client.members.list(params);
|
|
103
109
|
return response.data;
|
|
104
|
-
});
|
|
110
|
+
}, this.pacing);
|
|
105
111
|
members.push(...(page.members ?? []).map(convertToGroupMember));
|
|
106
112
|
pageToken = page.nextPageToken ?? undefined;
|
|
107
113
|
} while (pageToken);
|
|
@@ -121,7 +127,7 @@ export class DirectoryClient {
|
|
|
121
127
|
await safeCall(async () => {
|
|
122
128
|
const response = await this.client.members.insert({ groupKey, requestBody: { email, role } });
|
|
123
129
|
return response.data;
|
|
124
|
-
});
|
|
130
|
+
}, this.pacing);
|
|
125
131
|
winston.info("Added group member", { groupKey, email, role });
|
|
126
132
|
return "added";
|
|
127
133
|
}
|
|
@@ -143,7 +149,7 @@ export class DirectoryClient {
|
|
|
143
149
|
const member = await safeCall(async () => {
|
|
144
150
|
const response = await this.client.members.get({ groupKey, memberKey: email });
|
|
145
151
|
return response.data;
|
|
146
|
-
});
|
|
152
|
+
}, this.pacing);
|
|
147
153
|
const currentRole = member.role ?? "MEMBER";
|
|
148
154
|
if (GROUP_ROLE_RANK[currentRole] < GROUP_ROLE_RANK[role]) {
|
|
149
155
|
await this.updateMemberRole(groupKey, email, role);
|
|
@@ -157,7 +163,7 @@ export class DirectoryClient {
|
|
|
157
163
|
await safeCall(async () => {
|
|
158
164
|
const response = await this.client.members.update({ groupKey, memberKey: email, requestBody: { role } });
|
|
159
165
|
return response.data;
|
|
160
|
-
});
|
|
166
|
+
}, this.pacing);
|
|
161
167
|
winston.info("Updated group member role", { groupKey, email, role });
|
|
162
168
|
}
|
|
163
169
|
}
|
|
@@ -191,8 +197,14 @@ function convertToGroupMember(member) {
|
|
|
191
197
|
*/
|
|
192
198
|
export class GroupSettingsClient {
|
|
193
199
|
client;
|
|
194
|
-
|
|
195
|
-
|
|
200
|
+
pacing;
|
|
201
|
+
constructor(auth, options = {}) {
|
|
202
|
+
this.pacing = options.pacing ?? {};
|
|
203
|
+
this.client = google.groupssettings({
|
|
204
|
+
version: "v1",
|
|
205
|
+
auth,
|
|
206
|
+
rootUrl: options.rootUrl,
|
|
207
|
+
});
|
|
196
208
|
}
|
|
197
209
|
/**
|
|
198
210
|
* Gets a group's settings.
|
|
@@ -204,7 +216,7 @@ export class GroupSettingsClient {
|
|
|
204
216
|
// reads as undefined.
|
|
205
217
|
const response = await this.client.groups.get({ groupUniqueId: groupEmail, alt: "json" });
|
|
206
218
|
return response.data;
|
|
207
|
-
});
|
|
219
|
+
}, this.pacing);
|
|
208
220
|
}
|
|
209
221
|
/**
|
|
210
222
|
* Patches a group's settings from the given settings object.
|
|
@@ -218,7 +230,7 @@ export class GroupSettingsClient {
|
|
|
218
230
|
requestBody: settings,
|
|
219
231
|
});
|
|
220
232
|
return response.data;
|
|
221
|
-
});
|
|
233
|
+
}, this.pacing);
|
|
222
234
|
winston.info("Patched group settings", { groupEmail });
|
|
223
235
|
return result;
|
|
224
236
|
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/** The time the fake reads, in epoch milliseconds. */
|
|
2
|
+
export interface Clock {
|
|
3
|
+
now(): number;
|
|
4
|
+
}
|
|
5
|
+
export declare const systemClock: Clock;
|
|
6
|
+
/** A clock that moves only when told to, so a test can step past the fake's delays at once. */
|
|
7
|
+
export declare class ManualClock implements Clock {
|
|
8
|
+
private time;
|
|
9
|
+
constructor(time?: number);
|
|
10
|
+
now(): number;
|
|
11
|
+
advance(ms: number): void;
|
|
12
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export const systemClock = { now: () => Date.now() };
|
|
2
|
+
/** A clock that moves only when told to, so a test can step past the fake's delays at once. */
|
|
3
|
+
export class ManualClock {
|
|
4
|
+
time;
|
|
5
|
+
constructor(time = 0) {
|
|
6
|
+
this.time = time;
|
|
7
|
+
}
|
|
8
|
+
now() {
|
|
9
|
+
return this.time;
|
|
10
|
+
}
|
|
11
|
+
advance(ms) {
|
|
12
|
+
this.time += ms;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/** The JSON body Google's Directory and Groups Settings APIs send with an error. */
|
|
2
|
+
export interface GoogleErrorBody {
|
|
3
|
+
error: {
|
|
4
|
+
code: number;
|
|
5
|
+
message: string;
|
|
6
|
+
errors: {
|
|
7
|
+
message: string;
|
|
8
|
+
domain: string;
|
|
9
|
+
reason: string;
|
|
10
|
+
}[];
|
|
11
|
+
};
|
|
12
|
+
}
|
|
13
|
+
/** An error the fake answers with, carrying the status and body Google would send. */
|
|
14
|
+
export declare class FakeApiError extends Error {
|
|
15
|
+
readonly status: number;
|
|
16
|
+
readonly reason: string;
|
|
17
|
+
constructor(status: number, reason: string, message: string);
|
|
18
|
+
get body(): GoogleErrorBody;
|
|
19
|
+
}
|
|
20
|
+
/** A 404 naming the key it couldn't resolve, such as `groupKey` or `memberKey`. */
|
|
21
|
+
export declare function notFound(key: string): FakeApiError;
|
|
22
|
+
export declare function invalidInput(field: string): FakeApiError;
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/** An error the fake answers with, carrying the status and body Google would send. */
|
|
2
|
+
export class FakeApiError extends Error {
|
|
3
|
+
status;
|
|
4
|
+
reason;
|
|
5
|
+
constructor(status, reason, message) {
|
|
6
|
+
super(message);
|
|
7
|
+
this.status = status;
|
|
8
|
+
this.reason = reason;
|
|
9
|
+
this.name = "FakeApiError";
|
|
10
|
+
}
|
|
11
|
+
get body() {
|
|
12
|
+
return {
|
|
13
|
+
error: {
|
|
14
|
+
code: this.status,
|
|
15
|
+
message: this.message,
|
|
16
|
+
errors: [{ message: this.message, domain: "global", reason: this.reason }],
|
|
17
|
+
},
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
/** A 404 naming the key it couldn't resolve, such as `groupKey` or `memberKey`. */
|
|
22
|
+
export function notFound(key) {
|
|
23
|
+
return new FakeApiError(404, "notFound", `Resource Not Found: ${key}`);
|
|
24
|
+
}
|
|
25
|
+
export function invalidInput(field) {
|
|
26
|
+
return new FakeApiError(400, "invalid", `Invalid Input: ${field}`);
|
|
27
|
+
}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import type { GroupMemberType, GroupRole, GroupSettings } from "../directory.js";
|
|
2
|
+
import { type Clock } from "./clock.js";
|
|
3
|
+
export interface WorkspaceModelOptions {
|
|
4
|
+
clock?: Clock;
|
|
5
|
+
/** How long a new group refuses member inserts. Defaults to a minute. */
|
|
6
|
+
newGroupDelayMs?: number;
|
|
7
|
+
/** The largest page a list returns, and the default. Google's is 200. */
|
|
8
|
+
pageSize?: number;
|
|
9
|
+
}
|
|
10
|
+
/** Seeds state as if it was written long ago, past every delay. */
|
|
11
|
+
export interface SeedOptions {
|
|
12
|
+
settled?: boolean;
|
|
13
|
+
}
|
|
14
|
+
/** A Directory API group resource, as the fake sends it. */
|
|
15
|
+
export interface FakeGroup {
|
|
16
|
+
kind: "admin#directory#group";
|
|
17
|
+
id: string;
|
|
18
|
+
email: string;
|
|
19
|
+
name?: string;
|
|
20
|
+
description?: string;
|
|
21
|
+
directMembersCount: string;
|
|
22
|
+
adminCreated: boolean;
|
|
23
|
+
}
|
|
24
|
+
/** A Directory API member resource, as the fake sends it. */
|
|
25
|
+
export interface FakeMember {
|
|
26
|
+
kind: "admin#directory#member";
|
|
27
|
+
id: string;
|
|
28
|
+
email: string;
|
|
29
|
+
role: GroupRole;
|
|
30
|
+
type: GroupMemberType;
|
|
31
|
+
status?: "ACTIVE";
|
|
32
|
+
}
|
|
33
|
+
export interface ListParams {
|
|
34
|
+
pageToken?: string | undefined;
|
|
35
|
+
maxResults?: number | undefined;
|
|
36
|
+
}
|
|
37
|
+
export interface GroupPage {
|
|
38
|
+
kind: "admin#directory#groups";
|
|
39
|
+
groups?: FakeGroup[];
|
|
40
|
+
nextPageToken?: string;
|
|
41
|
+
}
|
|
42
|
+
export interface MemberPage {
|
|
43
|
+
kind: "admin#directory#members";
|
|
44
|
+
members?: FakeMember[];
|
|
45
|
+
nextPageToken?: string;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Google Workspace groups, members, and group settings, held in memory. Its methods mirror the
|
|
49
|
+
* Directory and Groups Settings API calls the SDK makes, and they throw {@link FakeApiError} where
|
|
50
|
+
* Google answers with an error.
|
|
51
|
+
*/
|
|
52
|
+
export declare class WorkspaceModel {
|
|
53
|
+
private readonly clock;
|
|
54
|
+
private readonly newGroupDelayMs;
|
|
55
|
+
private readonly pageSize;
|
|
56
|
+
private readonly groups;
|
|
57
|
+
private readonly userIds;
|
|
58
|
+
private nextId;
|
|
59
|
+
constructor(options?: WorkspaceModelOptions);
|
|
60
|
+
insertGroup(body: {
|
|
61
|
+
email?: string | null;
|
|
62
|
+
name?: string | null;
|
|
63
|
+
description?: string | null;
|
|
64
|
+
}, seed?: SeedOptions): FakeGroup;
|
|
65
|
+
getGroup(groupKey: string): FakeGroup;
|
|
66
|
+
/** Lists every group. The fake holds one customer, so `customer` only has to be present. */
|
|
67
|
+
listGroups(params: ListParams & {
|
|
68
|
+
customer?: string | undefined;
|
|
69
|
+
domain?: string | undefined;
|
|
70
|
+
}): GroupPage;
|
|
71
|
+
insertMember(groupKey: string, body: {
|
|
72
|
+
email?: string | null;
|
|
73
|
+
role?: string | null;
|
|
74
|
+
}, seed?: SeedOptions): FakeMember;
|
|
75
|
+
getMember(groupKey: string, memberKey: string): FakeMember;
|
|
76
|
+
listMembers(groupKey: string, params?: ListParams): MemberPage;
|
|
77
|
+
updateMember(groupKey: string, memberKey: string, body: {
|
|
78
|
+
role?: string | null;
|
|
79
|
+
}): FakeMember;
|
|
80
|
+
getSettings(groupUniqueId: string): GroupSettings;
|
|
81
|
+
patchSettings(groupUniqueId: string, patch: GroupSettings): GroupSettings;
|
|
82
|
+
private requireGroup;
|
|
83
|
+
private requireSettingsGroup;
|
|
84
|
+
private findGroup;
|
|
85
|
+
private requireMember;
|
|
86
|
+
/** Whether `target` is `from` or a group nested anywhere under it. */
|
|
87
|
+
private reaches;
|
|
88
|
+
private parseRole;
|
|
89
|
+
private page;
|
|
90
|
+
private newId;
|
|
91
|
+
/** A person keeps one ID across every group they're in, as they do in Google. */
|
|
92
|
+
private userId;
|
|
93
|
+
private toGroup;
|
|
94
|
+
private toMember;
|
|
95
|
+
private toSettings;
|
|
96
|
+
}
|
|
@@ -0,0 +1,312 @@
|
|
|
1
|
+
import { systemClock } from "./clock.js";
|
|
2
|
+
import { FakeApiError, invalidInput, notFound } from "./errors.js";
|
|
3
|
+
const ROLES = ["MEMBER", "MANAGER", "OWNER"];
|
|
4
|
+
/**
|
|
5
|
+
* Every field the settings templates set, so an untouched group reads like a real one. Google
|
|
6
|
+
* documents only `spamModerationLevel` and `messageDisplayFont`; the other values are guesses.
|
|
7
|
+
* `defaultMessageDenyNotificationText` is left out because Google omits it while it's empty.
|
|
8
|
+
*/
|
|
9
|
+
const DEFAULT_SETTINGS = {
|
|
10
|
+
allowExternalMembers: "false",
|
|
11
|
+
allowGoogleCommunication: "false",
|
|
12
|
+
allowWebPosting: "true",
|
|
13
|
+
archiveOnly: "false",
|
|
14
|
+
customFooterText: "",
|
|
15
|
+
customRolesEnabledForSettingsToBeMerged: "false",
|
|
16
|
+
default_sender: "DEFAULT_SELF",
|
|
17
|
+
enableCollaborativeInbox: "false",
|
|
18
|
+
favoriteRepliesOnTop: "true",
|
|
19
|
+
includeCustomFooter: "false",
|
|
20
|
+
includeInGlobalAddressList: "true",
|
|
21
|
+
isArchived: "false",
|
|
22
|
+
maxMessageBytes: 26214400,
|
|
23
|
+
membersCanPostAsTheGroup: "false",
|
|
24
|
+
messageDisplayFont: "DEFAULT_FONT",
|
|
25
|
+
messageModerationLevel: "MODERATE_NONE",
|
|
26
|
+
primaryLanguage: "en_US",
|
|
27
|
+
replyTo: "REPLY_TO_IGNORE",
|
|
28
|
+
sendMessageDenyNotification: "false",
|
|
29
|
+
showInGroupDirectory: "false",
|
|
30
|
+
spamModerationLevel: "MODERATE",
|
|
31
|
+
whoCanAdd: "ALL_MANAGERS_CAN_ADD",
|
|
32
|
+
whoCanAddReferences: "NONE",
|
|
33
|
+
whoCanApproveMembers: "ALL_MANAGERS_CAN_APPROVE",
|
|
34
|
+
whoCanApproveMessages: "OWNERS_AND_MANAGERS",
|
|
35
|
+
whoCanAssignTopics: "NONE",
|
|
36
|
+
whoCanAssistContent: "NONE",
|
|
37
|
+
whoCanBanUsers: "OWNERS_AND_MANAGERS",
|
|
38
|
+
whoCanContactOwner: "ANYONE_CAN_CONTACT",
|
|
39
|
+
whoCanDeleteAnyPost: "OWNERS_AND_MANAGERS",
|
|
40
|
+
whoCanDeleteTopics: "OWNERS_AND_MANAGERS",
|
|
41
|
+
whoCanDiscoverGroup: "ALL_IN_DOMAIN_CAN_DISCOVER",
|
|
42
|
+
whoCanEnterFreeFormTags: "NONE",
|
|
43
|
+
whoCanHideAbuse: "NONE",
|
|
44
|
+
whoCanInvite: "ALL_MANAGERS_CAN_INVITE",
|
|
45
|
+
whoCanJoin: "CAN_REQUEST_TO_JOIN",
|
|
46
|
+
whoCanLeaveGroup: "ALL_MEMBERS_CAN_LEAVE",
|
|
47
|
+
whoCanLockTopics: "OWNERS_AND_MANAGERS",
|
|
48
|
+
whoCanMakeTopicsSticky: "NONE",
|
|
49
|
+
whoCanMarkDuplicate: "NONE",
|
|
50
|
+
whoCanMarkFavoriteReplyOnAnyTopic: "NONE",
|
|
51
|
+
whoCanMarkFavoriteReplyOnOwnTopic: "NONE",
|
|
52
|
+
whoCanMarkNoResponseNeeded: "NONE",
|
|
53
|
+
whoCanModerateContent: "OWNERS_AND_MANAGERS",
|
|
54
|
+
whoCanModerateMembers: "OWNERS_AND_MANAGERS",
|
|
55
|
+
whoCanModifyMembers: "OWNERS_AND_MANAGERS",
|
|
56
|
+
whoCanModifyTagsAndCategories: "NONE",
|
|
57
|
+
whoCanMoveTopicsIn: "OWNERS_AND_MANAGERS",
|
|
58
|
+
whoCanMoveTopicsOut: "OWNERS_AND_MANAGERS",
|
|
59
|
+
whoCanPostAnnouncements: "OWNERS_AND_MANAGERS",
|
|
60
|
+
whoCanPostMessage: "ANYONE_CAN_POST",
|
|
61
|
+
whoCanTakeTopics: "NONE",
|
|
62
|
+
whoCanUnassignTopic: "NONE",
|
|
63
|
+
whoCanUnmarkFavoriteReplyOnAnyTopic: "NONE",
|
|
64
|
+
whoCanViewGroup: "ALL_MEMBERS_CAN_VIEW",
|
|
65
|
+
whoCanViewMembership: "ALL_MEMBERS_CAN_VIEW",
|
|
66
|
+
};
|
|
67
|
+
/**
|
|
68
|
+
* Google Workspace groups, members, and group settings, held in memory. Its methods mirror the
|
|
69
|
+
* Directory and Groups Settings API calls the SDK makes, and they throw {@link FakeApiError} where
|
|
70
|
+
* Google answers with an error.
|
|
71
|
+
*/
|
|
72
|
+
export class WorkspaceModel {
|
|
73
|
+
clock;
|
|
74
|
+
newGroupDelayMs;
|
|
75
|
+
pageSize;
|
|
76
|
+
groups = new Map();
|
|
77
|
+
userIds = new Map();
|
|
78
|
+
nextId = 1;
|
|
79
|
+
constructor(options = {}) {
|
|
80
|
+
this.clock = options.clock ?? systemClock;
|
|
81
|
+
this.newGroupDelayMs = options.newGroupDelayMs ?? 60_000;
|
|
82
|
+
this.pageSize = options.pageSize ?? 200;
|
|
83
|
+
}
|
|
84
|
+
insertGroup(body, seed = {}) {
|
|
85
|
+
if (!body.email) {
|
|
86
|
+
throw invalidInput("email");
|
|
87
|
+
}
|
|
88
|
+
const key = body.email.toLowerCase();
|
|
89
|
+
if (this.groups.has(key)) {
|
|
90
|
+
throw new FakeApiError(409, "duplicate", "Entity already exists.");
|
|
91
|
+
}
|
|
92
|
+
const group = {
|
|
93
|
+
id: this.newId("group"),
|
|
94
|
+
email: body.email,
|
|
95
|
+
acceptsMembersAt: seed.settled ? 0 : this.clock.now() + this.newGroupDelayMs,
|
|
96
|
+
settings: { ...DEFAULT_SETTINGS },
|
|
97
|
+
members: new Map(),
|
|
98
|
+
};
|
|
99
|
+
if (body.name) {
|
|
100
|
+
group.name = body.name;
|
|
101
|
+
}
|
|
102
|
+
if (body.description) {
|
|
103
|
+
group.description = body.description;
|
|
104
|
+
}
|
|
105
|
+
this.groups.set(key, group);
|
|
106
|
+
return this.toGroup(group);
|
|
107
|
+
}
|
|
108
|
+
getGroup(groupKey) {
|
|
109
|
+
return this.toGroup(this.requireGroup(groupKey));
|
|
110
|
+
}
|
|
111
|
+
/** Lists every group. The fake holds one customer, so `customer` only has to be present. */
|
|
112
|
+
listGroups(params) {
|
|
113
|
+
if (!params.customer && !params.domain) {
|
|
114
|
+
throw new FakeApiError(400, "badRequest", "Bad Request");
|
|
115
|
+
}
|
|
116
|
+
const all = [...this.groups.values()].sort((a, b) => a.email.localeCompare(b.email));
|
|
117
|
+
const { items, nextPageToken } = this.page(all, params);
|
|
118
|
+
// Google leaves the list out entirely when it's empty.
|
|
119
|
+
const page = { kind: "admin#directory#groups" };
|
|
120
|
+
if (items.length > 0) {
|
|
121
|
+
page.groups = items.map((group) => this.toGroup(group));
|
|
122
|
+
}
|
|
123
|
+
if (nextPageToken) {
|
|
124
|
+
page.nextPageToken = nextPageToken;
|
|
125
|
+
}
|
|
126
|
+
return page;
|
|
127
|
+
}
|
|
128
|
+
insertMember(groupKey, body, seed = {}) {
|
|
129
|
+
const group = this.requireGroup(groupKey);
|
|
130
|
+
if (!body.email) {
|
|
131
|
+
throw invalidInput("memberKey");
|
|
132
|
+
}
|
|
133
|
+
const role = this.parseRole(body.role ?? "MEMBER");
|
|
134
|
+
// A group too new to take members answers as if it didn't exist yet
|
|
135
|
+
// (googleapis/google-api-nodejs-client#166).
|
|
136
|
+
if (!seed.settled && this.clock.now() < group.acceptsMembersAt) {
|
|
137
|
+
throw notFound("groupKey");
|
|
138
|
+
}
|
|
139
|
+
const key = body.email.toLowerCase();
|
|
140
|
+
if (group.members.has(key)) {
|
|
141
|
+
throw new FakeApiError(409, "duplicate", "Member already exists.");
|
|
142
|
+
}
|
|
143
|
+
const nested = this.groups.get(key);
|
|
144
|
+
if (nested && this.reaches(nested, group)) {
|
|
145
|
+
// The reason and message GAM matches on (GAM-team/GAM src/gam/gamlib/glgapi.py). The status
|
|
146
|
+
// follows the JSON API's convention for conditionNotMet.
|
|
147
|
+
throw new FakeApiError(412, "conditionNotMet", "Cyclic memberships not allowed");
|
|
148
|
+
}
|
|
149
|
+
const member = nested
|
|
150
|
+
? { id: nested.id, email: nested.email, role, type: "GROUP" }
|
|
151
|
+
: { id: this.userId(key), email: body.email, role, type: "USER" };
|
|
152
|
+
group.members.set(key, member);
|
|
153
|
+
return this.toMember(member);
|
|
154
|
+
}
|
|
155
|
+
getMember(groupKey, memberKey) {
|
|
156
|
+
return this.toMember(this.requireMember(this.requireGroup(groupKey), memberKey));
|
|
157
|
+
}
|
|
158
|
+
listMembers(groupKey, params = {}) {
|
|
159
|
+
const group = this.requireGroup(groupKey);
|
|
160
|
+
const { items, nextPageToken } = this.page([...group.members.values()], params);
|
|
161
|
+
const page = { kind: "admin#directory#members" };
|
|
162
|
+
if (items.length > 0) {
|
|
163
|
+
page.members = items.map((member) => this.toMember(member));
|
|
164
|
+
}
|
|
165
|
+
if (nextPageToken) {
|
|
166
|
+
page.nextPageToken = nextPageToken;
|
|
167
|
+
}
|
|
168
|
+
return page;
|
|
169
|
+
}
|
|
170
|
+
updateMember(groupKey, memberKey, body) {
|
|
171
|
+
const member = this.requireMember(this.requireGroup(groupKey), memberKey);
|
|
172
|
+
if (body.role) {
|
|
173
|
+
member.role = this.parseRole(body.role);
|
|
174
|
+
}
|
|
175
|
+
return this.toMember(member);
|
|
176
|
+
}
|
|
177
|
+
getSettings(groupUniqueId) {
|
|
178
|
+
return this.toSettings(this.requireSettingsGroup(groupUniqueId));
|
|
179
|
+
}
|
|
180
|
+
patchSettings(groupUniqueId, patch) {
|
|
181
|
+
const group = this.requireSettingsGroup(groupUniqueId);
|
|
182
|
+
const fields = { ...patch };
|
|
183
|
+
delete fields.kind;
|
|
184
|
+
delete fields.email;
|
|
185
|
+
group.settings = { ...group.settings, ...fields };
|
|
186
|
+
return this.toSettings(group);
|
|
187
|
+
}
|
|
188
|
+
requireGroup(groupKey) {
|
|
189
|
+
const group = this.findGroup(groupKey);
|
|
190
|
+
if (!group) {
|
|
191
|
+
throw notFound("groupKey");
|
|
192
|
+
}
|
|
193
|
+
return group;
|
|
194
|
+
}
|
|
195
|
+
requireSettingsGroup(groupUniqueId) {
|
|
196
|
+
const group = this.findGroup(groupUniqueId);
|
|
197
|
+
if (!group) {
|
|
198
|
+
throw new FakeApiError(404, "notFound", "Not Found");
|
|
199
|
+
}
|
|
200
|
+
return group;
|
|
201
|
+
}
|
|
202
|
+
findGroup(key) {
|
|
203
|
+
const byEmail = this.groups.get(key.toLowerCase());
|
|
204
|
+
if (byEmail) {
|
|
205
|
+
return byEmail;
|
|
206
|
+
}
|
|
207
|
+
return [...this.groups.values()].find((group) => group.id === key);
|
|
208
|
+
}
|
|
209
|
+
requireMember(group, memberKey) {
|
|
210
|
+
const member = group.members.get(memberKey.toLowerCase()) ??
|
|
211
|
+
[...group.members.values()].find((candidate) => candidate.id === memberKey);
|
|
212
|
+
if (!member) {
|
|
213
|
+
throw notFound("memberKey");
|
|
214
|
+
}
|
|
215
|
+
return member;
|
|
216
|
+
}
|
|
217
|
+
/** Whether `target` is `from` or a group nested anywhere under it. */
|
|
218
|
+
reaches(from, target) {
|
|
219
|
+
const seen = new Set();
|
|
220
|
+
const stack = [from];
|
|
221
|
+
while (stack.length > 0) {
|
|
222
|
+
const group = stack.pop();
|
|
223
|
+
if (group === target) {
|
|
224
|
+
return true;
|
|
225
|
+
}
|
|
226
|
+
if (seen.has(group)) {
|
|
227
|
+
continue;
|
|
228
|
+
}
|
|
229
|
+
seen.add(group);
|
|
230
|
+
for (const member of group.members.values()) {
|
|
231
|
+
const nested = member.type === "GROUP" ? this.groups.get(member.email.toLowerCase()) : undefined;
|
|
232
|
+
if (nested) {
|
|
233
|
+
stack.push(nested);
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
return false;
|
|
238
|
+
}
|
|
239
|
+
parseRole(role) {
|
|
240
|
+
if (!ROLES.includes(role)) {
|
|
241
|
+
throw invalidInput("role");
|
|
242
|
+
}
|
|
243
|
+
return role;
|
|
244
|
+
}
|
|
245
|
+
page(items, params) {
|
|
246
|
+
const size = Math.min(params.maxResults ?? this.pageSize, this.pageSize);
|
|
247
|
+
if (!Number.isInteger(size) || size < 1) {
|
|
248
|
+
throw invalidInput("maxResults");
|
|
249
|
+
}
|
|
250
|
+
const start = params.pageToken ? decodePageToken(params.pageToken) : 0;
|
|
251
|
+
const end = start + size;
|
|
252
|
+
const result = { items: items.slice(start, end) };
|
|
253
|
+
if (end < items.length) {
|
|
254
|
+
result.nextPageToken = encodePageToken(end);
|
|
255
|
+
}
|
|
256
|
+
return result;
|
|
257
|
+
}
|
|
258
|
+
newId(prefix) {
|
|
259
|
+
return `fake-${prefix}-${this.nextId++}`;
|
|
260
|
+
}
|
|
261
|
+
/** A person keeps one ID across every group they're in, as they do in Google. */
|
|
262
|
+
userId(email) {
|
|
263
|
+
let id = this.userIds.get(email);
|
|
264
|
+
if (!id) {
|
|
265
|
+
id = this.newId("user");
|
|
266
|
+
this.userIds.set(email, id);
|
|
267
|
+
}
|
|
268
|
+
return id;
|
|
269
|
+
}
|
|
270
|
+
toGroup(group) {
|
|
271
|
+
const result = {
|
|
272
|
+
kind: "admin#directory#group",
|
|
273
|
+
id: group.id,
|
|
274
|
+
email: group.email,
|
|
275
|
+
directMembersCount: String(group.members.size),
|
|
276
|
+
adminCreated: true,
|
|
277
|
+
};
|
|
278
|
+
if (group.name) {
|
|
279
|
+
result.name = group.name;
|
|
280
|
+
}
|
|
281
|
+
if (group.description) {
|
|
282
|
+
result.description = group.description;
|
|
283
|
+
}
|
|
284
|
+
return result;
|
|
285
|
+
}
|
|
286
|
+
toMember(member) {
|
|
287
|
+
const result = {
|
|
288
|
+
kind: "admin#directory#member",
|
|
289
|
+
id: member.id,
|
|
290
|
+
email: member.email,
|
|
291
|
+
role: member.role,
|
|
292
|
+
type: member.type,
|
|
293
|
+
};
|
|
294
|
+
if (member.type === "USER") {
|
|
295
|
+
result.status = "ACTIVE";
|
|
296
|
+
}
|
|
297
|
+
return result;
|
|
298
|
+
}
|
|
299
|
+
toSettings(group) {
|
|
300
|
+
return { kind: "groupsSettings#groups", email: group.email, ...group.settings };
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
function encodePageToken(offset) {
|
|
304
|
+
return Buffer.from(String(offset)).toString("base64url");
|
|
305
|
+
}
|
|
306
|
+
function decodePageToken(token) {
|
|
307
|
+
const offset = Number(Buffer.from(token, "base64url").toString());
|
|
308
|
+
if (!Number.isInteger(offset) || offset < 0) {
|
|
309
|
+
throw invalidInput("pageToken");
|
|
310
|
+
}
|
|
311
|
+
return offset;
|
|
312
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { type Server } from "node:http";
|
|
2
|
+
import { WorkspaceModel } from "./model.js";
|
|
3
|
+
/** An HTTP server that answers like Google's Directory and Groups Settings APIs, over `model`. */
|
|
4
|
+
export declare function createFakeServer(model: WorkspaceModel): Server;
|
|
5
|
+
export interface StartFakeServerOptions {
|
|
6
|
+
model?: WorkspaceModel;
|
|
7
|
+
host?: string;
|
|
8
|
+
/** 0, the default, picks a free port. */
|
|
9
|
+
port?: number;
|
|
10
|
+
}
|
|
11
|
+
export interface RunningFakeServer {
|
|
12
|
+
/** Pass this as the clients' `rootUrl`. */
|
|
13
|
+
rootUrl: string;
|
|
14
|
+
model: WorkspaceModel;
|
|
15
|
+
close(): Promise<void>;
|
|
16
|
+
}
|
|
17
|
+
/** Starts a fake server, by default on a free loopback port, and says where it listens. */
|
|
18
|
+
export declare function startFakeServer(options?: StartFakeServerOptions): Promise<RunningFakeServer>;
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
import { createServer } from "node:http";
|
|
2
|
+
import { FakeApiError } from "./errors.js";
|
|
3
|
+
import { WorkspaceModel } from "./model.js";
|
|
4
|
+
const SEGMENT = "([^/]+)";
|
|
5
|
+
/** Exactly the Directory and Groups Settings calls the SDK makes. */
|
|
6
|
+
const ROUTES = [
|
|
7
|
+
{
|
|
8
|
+
method: "GET",
|
|
9
|
+
path: new RegExp(`^/admin/directory/v1/groups$`),
|
|
10
|
+
handle: (model, _, url) => model.listGroups({
|
|
11
|
+
customer: query(url, "customer"),
|
|
12
|
+
domain: query(url, "domain"),
|
|
13
|
+
pageToken: query(url, "pageToken"),
|
|
14
|
+
maxResults: numberQuery(url, "maxResults"),
|
|
15
|
+
}),
|
|
16
|
+
},
|
|
17
|
+
{
|
|
18
|
+
method: "POST",
|
|
19
|
+
path: new RegExp(`^/admin/directory/v1/groups$`),
|
|
20
|
+
handle: (model, _, __, body) => model.insertGroup(asObject(body)),
|
|
21
|
+
},
|
|
22
|
+
{
|
|
23
|
+
method: "GET",
|
|
24
|
+
path: new RegExp(`^/admin/directory/v1/groups/${SEGMENT}$`),
|
|
25
|
+
handle: (model, [groupKey]) => model.getGroup(groupKey),
|
|
26
|
+
},
|
|
27
|
+
{
|
|
28
|
+
method: "GET",
|
|
29
|
+
path: new RegExp(`^/admin/directory/v1/groups/${SEGMENT}/members$`),
|
|
30
|
+
handle: (model, [groupKey], url) => model.listMembers(groupKey, {
|
|
31
|
+
pageToken: query(url, "pageToken"),
|
|
32
|
+
maxResults: numberQuery(url, "maxResults"),
|
|
33
|
+
}),
|
|
34
|
+
},
|
|
35
|
+
{
|
|
36
|
+
method: "POST",
|
|
37
|
+
path: new RegExp(`^/admin/directory/v1/groups/${SEGMENT}/members$`),
|
|
38
|
+
handle: (model, [groupKey], _, body) => model.insertMember(groupKey, asObject(body)),
|
|
39
|
+
},
|
|
40
|
+
{
|
|
41
|
+
method: "GET",
|
|
42
|
+
path: new RegExp(`^/admin/directory/v1/groups/${SEGMENT}/members/${SEGMENT}$`),
|
|
43
|
+
handle: (model, [groupKey, memberKey]) => model.getMember(groupKey, memberKey),
|
|
44
|
+
},
|
|
45
|
+
{
|
|
46
|
+
method: "PUT",
|
|
47
|
+
path: new RegExp(`^/admin/directory/v1/groups/${SEGMENT}/members/${SEGMENT}$`),
|
|
48
|
+
handle: (model, [groupKey, memberKey], _, body) => model.updateMember(groupKey, memberKey, asObject(body)),
|
|
49
|
+
},
|
|
50
|
+
{
|
|
51
|
+
method: "GET",
|
|
52
|
+
path: new RegExp(`^/groups/v1/groups/${SEGMENT}$`),
|
|
53
|
+
handle: (model, [groupUniqueId]) => model.getSettings(groupUniqueId),
|
|
54
|
+
},
|
|
55
|
+
{
|
|
56
|
+
method: "PATCH",
|
|
57
|
+
path: new RegExp(`^/groups/v1/groups/${SEGMENT}$`),
|
|
58
|
+
handle: (model, [groupUniqueId], _, body) => model.patchSettings(groupUniqueId, asObject(body)),
|
|
59
|
+
},
|
|
60
|
+
];
|
|
61
|
+
/** An HTTP server that answers like Google's Directory and Groups Settings APIs, over `model`. */
|
|
62
|
+
export function createFakeServer(model) {
|
|
63
|
+
return createServer((request, response) => {
|
|
64
|
+
handle(model, request, response).catch((error) => {
|
|
65
|
+
sendError(response, new FakeApiError(500, "backendError", String(error)));
|
|
66
|
+
});
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
/** Starts a fake server, by default on a free loopback port, and says where it listens. */
|
|
70
|
+
export async function startFakeServer(options = {}) {
|
|
71
|
+
const model = options.model ?? new WorkspaceModel();
|
|
72
|
+
const host = options.host ?? "127.0.0.1";
|
|
73
|
+
const server = createFakeServer(model);
|
|
74
|
+
await new Promise((resolve, reject) => {
|
|
75
|
+
server.once("error", reject);
|
|
76
|
+
server.listen(options.port ?? 0, host, () => resolve());
|
|
77
|
+
});
|
|
78
|
+
const { port } = server.address();
|
|
79
|
+
return {
|
|
80
|
+
rootUrl: `http://${host.includes(":") ? `[${host}]` : host}:${port}/`,
|
|
81
|
+
model,
|
|
82
|
+
close: () => new Promise((resolve, reject) => {
|
|
83
|
+
server.close((error) => (error ? reject(error) : resolve()));
|
|
84
|
+
server.closeAllConnections();
|
|
85
|
+
}),
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
async function handle(model, request, response) {
|
|
89
|
+
const url = new URL(request.url ?? "/", "http://fake");
|
|
90
|
+
const route = ROUTES.find((candidate) => candidate.method === request.method && candidate.path.test(url.pathname));
|
|
91
|
+
if (!route) {
|
|
92
|
+
sendError(response, new FakeApiError(404, "notFound", "Not Found"));
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
const raw = await readBody(request);
|
|
96
|
+
let body;
|
|
97
|
+
try {
|
|
98
|
+
body = raw ? JSON.parse(raw) : undefined;
|
|
99
|
+
}
|
|
100
|
+
catch {
|
|
101
|
+
sendError(response, new FakeApiError(400, "parseError", "Parse Error"));
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
let match;
|
|
105
|
+
try {
|
|
106
|
+
match = route.path.exec(url.pathname).slice(1).map(decodeURIComponent);
|
|
107
|
+
}
|
|
108
|
+
catch {
|
|
109
|
+
sendError(response, new FakeApiError(400, "badRequest", "Bad Request"));
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
try {
|
|
113
|
+
const result = route.handle(model, match, url, body);
|
|
114
|
+
if (url.pathname.startsWith("/groups/v1/") && url.searchParams.get("alt") !== "json") {
|
|
115
|
+
sendAtom(response, result);
|
|
116
|
+
}
|
|
117
|
+
else {
|
|
118
|
+
send(response, 200, result);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
catch (error) {
|
|
122
|
+
if (error instanceof FakeApiError) {
|
|
123
|
+
sendError(response, error);
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
throw error;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
function send(response, status, body) {
|
|
130
|
+
response.writeHead(status, { "Content-Type": "application/json; charset=UTF-8" });
|
|
131
|
+
response.end(JSON.stringify(body));
|
|
132
|
+
}
|
|
133
|
+
// Groups Settings answers in Atom unless asked for JSON. So does the fake, so a client that forgets
|
|
134
|
+
// `alt=json` fails here as it would against Google.
|
|
135
|
+
function sendAtom(response, settings) {
|
|
136
|
+
const fields = Object.entries(settings)
|
|
137
|
+
.filter(([key]) => key !== "kind")
|
|
138
|
+
.map(([key, value]) => `<apps:${key}>${escapeXml(String(value))}</apps:${key}>`)
|
|
139
|
+
.join("");
|
|
140
|
+
response.writeHead(200, { "Content-Type": "application/atom+xml; charset=UTF-8" });
|
|
141
|
+
response.end(`<?xml version="1.0" encoding="UTF-8"?><entry xmlns="http://www.w3.org/2005/Atom" xmlns:apps="http://schemas.google.com/apps/2006">${fields}</entry>`);
|
|
142
|
+
}
|
|
143
|
+
function escapeXml(value) {
|
|
144
|
+
return value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
145
|
+
}
|
|
146
|
+
function sendError(response, error) {
|
|
147
|
+
send(response, error.status, error.body);
|
|
148
|
+
}
|
|
149
|
+
async function readBody(request) {
|
|
150
|
+
const chunks = [];
|
|
151
|
+
for await (const chunk of request) {
|
|
152
|
+
chunks.push(chunk);
|
|
153
|
+
}
|
|
154
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
155
|
+
}
|
|
156
|
+
function query(url, name) {
|
|
157
|
+
return url.searchParams.get(name) ?? undefined;
|
|
158
|
+
}
|
|
159
|
+
function numberQuery(url, name) {
|
|
160
|
+
const value = url.searchParams.get(name);
|
|
161
|
+
return value === null ? undefined : Number(value);
|
|
162
|
+
}
|
|
163
|
+
function asObject(body) {
|
|
164
|
+
return typeof body === "object" && body !== null ? body : {};
|
|
165
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cyc-seattle/gsuite-sdk",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "Domain-agnostic wrappers around Google Workspace APIs",
|
|
5
5
|
"author": "CYC Community Sailing Center",
|
|
6
6
|
"license": "Apache-2.0",
|
|
@@ -26,10 +26,15 @@
|
|
|
26
26
|
"types": "./dist/index.d.ts",
|
|
27
27
|
"default": "./dist/index.js"
|
|
28
28
|
},
|
|
29
|
+
"./fake": {
|
|
30
|
+
"types": "./dist/fake/index.d.ts",
|
|
31
|
+
"default": "./dist/fake/index.js"
|
|
32
|
+
},
|
|
29
33
|
"./package.json": "./package.json"
|
|
30
34
|
},
|
|
31
35
|
"files": [
|
|
32
|
-
"dist"
|
|
36
|
+
"dist",
|
|
37
|
+
"!dist/fake/main.*"
|
|
33
38
|
],
|
|
34
39
|
"scripts": {
|
|
35
40
|
"build": "tsc -p tsconfig.build.json",
|
|
@@ -43,12 +48,13 @@
|
|
|
43
48
|
"winston": "^3.18.3"
|
|
44
49
|
},
|
|
45
50
|
"devDependencies": {
|
|
51
|
+
"@amiceli/vitest-cucumber": "^8.0.0",
|
|
46
52
|
"@cyc-seattle/ts-config": "^0.1.2",
|
|
47
53
|
"@types/luxon": "^3.7.1",
|
|
48
54
|
"@types/node": "^22.20.5",
|
|
49
55
|
"eslint": "^9.39.5",
|
|
50
56
|
"prettier": "^3.9.10",
|
|
51
57
|
"typescript": "^5.9.3",
|
|
52
|
-
"vitest": "^
|
|
58
|
+
"vitest": "^5.0.4"
|
|
53
59
|
}
|
|
54
60
|
}
|