@open-workspace/create 0.4.2 → 0.5.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.
Files changed (46) hide show
  1. package/README.md +9 -5
  2. package/dist/backup-schema.ts +110 -0
  3. package/dist/workspace.ts +162 -0
  4. package/import/backup-snapshot.ts +254 -0
  5. package/import/backup-source.ts +270 -0
  6. package/import/cli.ts +134 -90
  7. package/import/concurrency.ts +34 -37
  8. package/import/csv.ts +1 -1
  9. package/import/directory/command.ts +293 -72
  10. package/import/directory/google.ts +158 -120
  11. package/import/directory/invitation-file.ts +108 -0
  12. package/import/directory/plan.ts +314 -38
  13. package/import/directory/read.ts +55 -0
  14. package/import/gmail.ts +9 -12
  15. package/import/headers.ts +1 -1
  16. package/import/idp/apps.ts +244 -0
  17. package/import/idp/command.ts +161 -0
  18. package/import/idp/csv.ts +70 -0
  19. package/import/idp/entra.ts +297 -0
  20. package/import/idp/keycloak.ts +250 -0
  21. package/import/idp/model.ts +108 -0
  22. package/import/idp/okta.ts +159 -0
  23. package/import/idp/pages.ts +65 -0
  24. package/import/imap-command.ts +42 -18
  25. package/import/imap-source.ts +245 -220
  26. package/import/invariant.ts +1 -1
  27. package/import/loopback.ts +136 -0
  28. package/import/mbox-source.ts +106 -55
  29. package/import/mbox.ts +1 -1
  30. package/import/oauth.ts +234 -138
  31. package/import/preview.ts +48 -0
  32. package/import/uploader.ts +169 -115
  33. package/import/workspace.ts +78 -15
  34. package/index.ts +3 -0
  35. package/module-templates.ts +9 -12
  36. package/module.ts +1 -5
  37. package/package.json +13 -2
  38. package/setup/alchemy.ts +2 -2
  39. package/setup/args.ts +16 -17
  40. package/setup/cloudflare-api.ts +75 -19
  41. package/setup/domains.ts +18 -6
  42. package/setup/flow.ts +217 -58
  43. package/setup/migration-guide.ts +255 -0
  44. package/setup/mx-recovery.ts +115 -0
  45. package/setup/ui.ts +4 -1
  46. package/templates.ts +26 -18
@@ -1,16 +1,24 @@
1
- import { appendFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";
1
+ import {
2
+ appendFileSync,
3
+ existsSync,
4
+ mkdirSync,
5
+ readFileSync,
6
+ rmSync,
7
+ } from "node:fs";
2
8
  import { join } from "node:path";
3
9
 
4
10
  import { forEachConcurrent } from "./concurrency.ts";
5
11
  import { MAX_IMPORT_MESSAGE_BYTES } from "./protocol.ts";
6
12
  import type { ImportItem, SkippedItem } from "./protocol.ts";
7
- import { WorkspaceError } from "./workspace.ts";
13
+ import { failureKind, sendWithRetry } from "./workspace.ts";
8
14
  import type { Workspace } from "./workspace.ts";
9
15
 
10
16
  /**
11
- * What a run already did, so it can resume: one file of imported source
12
- * ids (appended as each message lands) and one of failures, per import job.
13
- * Failed messages are tried again on the next run.
17
+ * What a run already did, so it can resume: one file of the source ids
18
+ * the workspace has (appended as each lands: stored now or before) and
19
+ * one of failures, per import job. Only those are done; anything else
20
+ * (failed, or skipped by the source or the workspace) is tried again on
21
+ * the next run.
14
22
  */
15
23
  export class ResumeState {
16
24
  private readonly done = new Set<string>();
@@ -51,183 +59,229 @@ export class ResumeState {
51
59
  );
52
60
  }
53
61
 
62
+ clearProgress() {
63
+ rmSync(this.donePath, { force: true });
64
+ this.done.clear();
65
+ }
66
+
54
67
  get failuresPath() {
55
68
  return this.failedPath;
56
69
  }
57
70
  }
58
71
 
59
- export type UploadStats = {
60
- /** Messages the source has, when it was counted first. */
72
+ /** What a resumable run did; `progressLine` reports it. */
73
+ export type RunStats = {
74
+ /** Items the source has, when it was counted first. */
61
75
  total: number | null;
62
76
  seen: number;
63
- imported: number;
64
- duplicate: number;
65
- /** Already imported by an earlier run. */
77
+ /** Items that landed, by kind (imported, duplicate; restored, exists). */
78
+ done: Record<string, number>;
79
+ /** Done by an earlier run. */
66
80
  resumed: number;
67
- skipped: number;
81
+ /** Skipped by the source or the workspace, by reason; tried again next run. */
82
+ skipped: Map<string, number>;
68
83
  failed: number;
69
84
  bytes: number;
70
- /** Labels that could not become folders (the folder limit, or a system folder's name). */
71
- folderSkipped: number;
72
85
  };
73
86
 
74
- /** Errors worth trying again: the network, rate limits, the server having a bad moment. */
75
- function retryable(cause: unknown) {
76
- if (cause instanceof WorkspaceError) {
77
- return cause.status === 429 || cause.status >= 500;
78
- }
79
-
80
- return true;
81
- }
87
+ /** What sending one item came to: landed as a kind, skipped, or failed for this item alone. */
88
+ export type SendOutcome =
89
+ | { done: string }
90
+ | { skipped: string }
91
+ | { failed: string };
82
92
 
83
- /** Errors that end the run: every message would fail the same way. */
84
- function fatal(cause: unknown) {
85
- return (
86
- cause instanceof WorkspaceError && [401, 403, 404].includes(cause.status)
87
- );
88
- }
89
-
90
- /** What the uploader needs from the workspace; tests give a stand-in. */
91
- export type ImportDestination = Pick<
92
- Workspace,
93
- "importMessage" | "finishImport"
94
- >;
95
-
96
- export type UploadOptions = {
97
- workspace: ImportDestination;
98
- mailboxId: string;
99
- items:
100
- | AsyncIterable<ImportItem | SkippedItem>
101
- | Iterable<ImportItem | SkippedItem>;
93
+ export type RunOptions<T extends { sourceId: string }> = {
94
+ items: AsyncIterable<T | SkippedItem> | Iterable<T | SkippedItem>;
102
95
  state: ResumeState;
103
- /** Requests in flight; a mailbox stores one message at a time, so 2–4 is plenty. */
96
+ /** Requests in flight. */
104
97
  concurrency: number;
98
+ exclusive?: (item: T | SkippedItem) => boolean;
105
99
  total?: number | null;
100
+ /** Sends one item; a failure that may pass is tried again (`sendWithRetry`). */
101
+ send: (item: T) => Promise<SendOutcome>;
102
+ /** The bytes an item sends, for the progress line. */
103
+ size?: (item: T) => number;
106
104
  retries?: number;
107
105
  /** Delay before retry `attempt` (from 1); tests make it short. */
108
106
  backoff?: (attempt: number) => number;
109
- onProgress?: (stats: UploadStats) => void;
107
+ onProgress?: (stats: RunStats) => void;
110
108
  };
111
109
 
112
110
  /**
113
- * Uploads every item with bounded concurrency, retrying transient failures
114
- * and recording each result, then announces the batch to the mailbox.
111
+ * The one resumable run every import and restore makes: each item not done
112
+ * before is sent with bounded concurrency, failures that may pass are
113
+ * retried, and only what landed is recorded as done. A fatal failure ends
114
+ * the run.
115
115
  */
116
- export async function upload(options: UploadOptions): Promise<UploadStats> {
117
- const stats: UploadStats = {
116
+ export async function runResumable<T extends { sourceId: string }>(
117
+ options: RunOptions<T>
118
+ ) {
119
+ const stats: RunStats = {
118
120
  total: options.total ?? null,
119
121
  seen: 0,
120
- imported: 0,
121
- duplicate: 0,
122
+ done: {},
122
123
  resumed: 0,
123
- skipped: 0,
124
+ skipped: new Map(),
124
125
  failed: 0,
125
126
  bytes: 0,
126
- folderSkipped: 0,
127
127
  };
128
128
 
129
- const retries = options.retries ?? 6;
129
+ const skip = (reason: string) =>
130
+ stats.skipped.set(reason, (stats.skipped.get(reason) ?? 0) + 1);
131
+
132
+ const fail = (sourceId: string, reason: string) => {
133
+ stats.failed += 1;
134
+ options.state.fail(sourceId, reason);
135
+ };
136
+
137
+ const handle = async (item: T | SkippedItem) => {
138
+ stats.seen += 1;
139
+
140
+ if (options.state.has(item.sourceId)) {
141
+ stats.resumed += 1;
130
142
 
131
- const backoff =
132
- options.backoff ??
133
- ((attempt) => Math.min(30_000, 1000 * 2 ** (attempt - 1)));
143
+ return;
144
+ }
134
145
 
135
- const progress = () => options.onProgress?.(stats);
146
+ if ("skipped" in item) {
147
+ skip(item.skipped);
148
+
149
+ return;
150
+ }
136
151
 
137
- /** Sends one message, retrying transient failures; a fatal one rejects and ends the run. */
138
- const send = async (item: ImportItem, attempt = 1): Promise<void> => {
139
152
  try {
140
- const result = await options.workspace.importMessage(
141
- options.mailboxId,
142
- item
143
- );
153
+ const outcome = await sendWithRetry(() => options.send(item), {
154
+ retries: options.retries,
155
+ backoff: options.backoff,
156
+ });
144
157
 
145
- if (result.status === "duplicate") stats.duplicate += 1;
146
- else {
147
- stats.imported += 1;
158
+ if ("skipped" in outcome) {
159
+ skip(outcome.skipped);
148
160
 
149
- if (result.folderSkipped) stats.folderSkipped += 1;
161
+ return;
150
162
  }
151
163
 
152
- stats.bytes += item.raw.byteLength;
153
- options.state.add(item.sourceId);
154
- } catch (error) {
155
- if (fatal(error)) throw error;
156
-
157
- if (!retryable(error) || attempt > retries) {
158
- stats.failed += 1;
159
- options.state.fail(
160
- item.sourceId,
161
- error instanceof Error ? error.message : String(error)
162
- );
164
+ if ("failed" in outcome) {
165
+ fail(item.sourceId, outcome.failed);
163
166
 
164
167
  return;
165
168
  }
166
169
 
167
- await Bun.sleep(backoff(attempt));
170
+ stats.done[outcome.done] = (stats.done[outcome.done] ?? 0) + 1;
171
+ stats.bytes += options.size?.(item) ?? 0;
172
+ options.state.add(item.sourceId);
173
+ } catch (error) {
174
+ if (failureKind(error) === "fatal") throw error;
168
175
 
169
- return send(item, attempt + 1);
176
+ fail(
177
+ item.sourceId,
178
+ error instanceof Error ? error.message : String(error)
179
+ );
170
180
  }
171
181
  };
172
182
 
173
- const handle = async (item: ImportItem | SkippedItem) => {
174
- stats.seen += 1;
183
+ await forEachConcurrent(
184
+ options.items,
185
+ options.concurrency,
186
+ async (item) => {
187
+ try {
188
+ await handle(item);
189
+ } finally {
190
+ options.onProgress?.(stats);
191
+ }
192
+ },
193
+ options.exclusive
194
+ );
175
195
 
176
- if (options.state.has(item.sourceId)) {
177
- stats.resumed += 1;
178
- progress();
196
+ return stats;
197
+ }
179
198
 
180
- return;
181
- }
199
+ /** What the uploader needs from the workspace; tests give a stand-in. */
200
+ export type ImportDestination = Pick<
201
+ Workspace,
202
+ "importMessage" | "finishImport"
203
+ >;
182
204
 
183
- if ("skipped" in item) {
184
- stats.skipped += 1;
185
- progress();
205
+ export type UploadOptions = Omit<RunOptions<ImportItem>, "send" | "size"> & {
206
+ workspace: ImportDestination;
207
+ mailboxId: string;
208
+ };
186
209
 
187
- return;
188
- }
210
+ /** How the progress line names what an upload did. */
211
+ export const UPLOAD_OUTCOMES = {
212
+ imported: "imported",
213
+ // Its label could not become a folder (the folder limit, or a system
214
+ // folder's name).
215
+ importedWithoutFolder: "imported without their folder",
216
+ duplicate: "already there",
217
+ };
189
218
 
190
- if (item.raw.byteLength > MAX_IMPORT_MESSAGE_BYTES) {
191
- stats.failed += 1;
192
- options.state.fail(
193
- item.sourceId,
194
- `Larger than ${MAX_IMPORT_MESSAGE_BYTES / 1024 / 1024} MiB`
219
+ /**
220
+ * Uploads every message into one mailbox (`runResumable`), then announces
221
+ * the batch to the mailbox.
222
+ */
223
+ export async function upload(options: UploadOptions) {
224
+ const stats = await runResumable({
225
+ ...options,
226
+ size: (item) => item.raw.byteLength,
227
+ send: async (item) => {
228
+ if (item.raw.byteLength > MAX_IMPORT_MESSAGE_BYTES) {
229
+ return {
230
+ failed: `Larger than ${MAX_IMPORT_MESSAGE_BYTES / 1024 / 1024} MiB`,
231
+ };
232
+ }
233
+
234
+ const result = await options.workspace.importMessage(
235
+ options.mailboxId,
236
+ item
195
237
  );
196
- progress();
197
238
 
198
- return;
199
- }
239
+ if (result.status === "duplicate") return { done: "duplicate" };
200
240
 
201
- try {
202
- await send(item);
203
- } finally {
204
- progress();
205
- }
206
- };
241
+ return {
242
+ done: result.folderSkipped ? "importedWithoutFolder" : "imported",
243
+ };
244
+ },
245
+ });
207
246
 
208
- await forEachConcurrent(options.items, options.concurrency, handle);
209
247
  await options.workspace.finishImport(options.mailboxId);
210
248
 
211
249
  return stats;
212
250
  }
213
251
 
214
- /** A one-line progress report for a terminal. */
215
- export function progressLine(label: string, stats: UploadStats) {
252
+ function sum(values: Iterable<number>) {
253
+ let total = 0;
254
+
255
+ for (const value of values) total += value;
256
+
257
+ return total;
258
+ }
259
+
260
+ /**
261
+ * A one-line progress report for a terminal; `outcomes` names each kind
262
+ * of item that landed, the first always shown.
263
+ */
264
+ export function progressLine(
265
+ label: string,
266
+ stats: RunStats,
267
+ outcomes: Record<string, string>
268
+ ) {
269
+ const skipped = sum(stats.skipped.values());
270
+
216
271
  const done =
217
- stats.imported +
218
- stats.duplicate +
219
- stats.resumed +
220
- stats.skipped +
221
- stats.failed;
272
+ sum(Object.values(stats.done)) + stats.resumed + skipped + stats.failed;
222
273
 
223
274
  const of = stats.total === null ? "" : `/${stats.total}`;
224
- const parts = [`${stats.imported} imported`];
225
275
 
226
- if (stats.duplicate) parts.push(`${stats.duplicate} already there`);
276
+ const parts = Object.entries(outcomes).flatMap(([kind, name], index) => {
277
+ const count = stats.done[kind] ?? 0;
278
+
279
+ return count || index === 0 ? [`${count} ${name}`] : [];
280
+ });
227
281
 
228
282
  if (stats.resumed) parts.push(`${stats.resumed} done before`);
229
283
 
230
- if (stats.skipped) parts.push(`${stats.skipped} skipped`);
284
+ if (skipped) parts.push(`${skipped} skipped`);
231
285
 
232
286
  if (stats.failed) parts.push(`${stats.failed} failed`);
233
287
 
@@ -1,8 +1,9 @@
1
1
  import { z } from "zod";
2
2
 
3
+ import { SignInError } from "./oauth.ts";
3
4
  import type { Fetch, TokenSource } from "./oauth.ts";
4
5
  import { importTargetSchema } from "./protocol.ts";
5
- import type { ImportItem } from "./protocol.ts";
6
+ import type { ImportItem, ImportTarget } from "./protocol.ts";
6
7
 
7
8
  export class WorkspaceError extends Error {
8
9
  constructor(
@@ -15,6 +16,53 @@ export class WorkspaceError extends Error {
15
16
  }
16
17
  }
17
18
 
19
+ export function isSignInFailure(cause: unknown) {
20
+ return (
21
+ cause instanceof SignInError ||
22
+ (cause instanceof WorkspaceError && cause.status === 401)
23
+ );
24
+ }
25
+
26
+ /**
27
+ * What a failed request means for an import, the same for every source:
28
+ * `fatal` ends the run (every item would fail the same way: the sign-in,
29
+ * the permission, the mailbox gone), `retry` may pass (the network, rate
30
+ * limits, a bad moment), `item` is this one item's.
31
+ */
32
+ export function failureKind(cause: unknown) {
33
+ if (isSignInFailure(cause)) return "fatal";
34
+
35
+ if (!(cause instanceof WorkspaceError)) return "retry";
36
+
37
+ if ([403, 404].includes(cause.status)) return "fatal";
38
+
39
+ return cause.status === 429 || cause.status >= 500 ? "retry" : "item";
40
+ }
41
+
42
+ /**
43
+ * Runs `attempt` until it succeeds, trying again a failure that may pass
44
+ * up to `retries` times with growing waits; any other failure, or the last
45
+ * one, is thrown (`failureKind` says which ends the run).
46
+ */
47
+ export async function sendWithRetry<T>(
48
+ attempt: () => Promise<T>,
49
+ {
50
+ retries = 6,
51
+ backoff = (tried: number) => Math.min(30_000, 1000 * 2 ** (tried - 1)),
52
+ }: { retries?: number; backoff?: (attempt: number) => number } = {}
53
+ ) {
54
+ for (let tried = 1; ; tried += 1) {
55
+ try {
56
+ // oxlint-disable-next-line eslint/no-await-in-loop -- a retry waits for the attempt before it
57
+ return await attempt();
58
+ } catch (error) {
59
+ if (failureKind(error) !== "retry" || tried > retries) throw error;
60
+ // oxlint-disable-next-line eslint/no-await-in-loop -- see above
61
+ await Bun.sleep(backoff(tried));
62
+ }
63
+ }
64
+ }
65
+
18
66
  export type ImportResult =
19
67
  | {
20
68
  status: "imported";
@@ -27,6 +75,7 @@ export type ImportResult =
27
75
  /** The workspace's HTTP API, signed in with an OAuth token. */
28
76
  export class Workspace {
29
77
  readonly origin: string;
78
+ private importMailboxes?: ImportTarget[];
30
79
 
31
80
  constructor(
32
81
  workspace: string,
@@ -37,7 +86,7 @@ export class Workspace {
37
86
  }
38
87
 
39
88
  /** A request with the token; a refused token is refreshed once. */
40
- async request(path: string, init: RequestInit = {}): Promise<Response> {
89
+ async request(path: string, init: RequestInit = {}) {
41
90
  const send = (token: string) => {
42
91
  const headers = new Headers(init.headers);
43
92
  headers.set("authorization", `Bearer ${token}`);
@@ -45,12 +94,13 @@ export class Workspace {
45
94
  return this.fetchImpl(`${this.origin}${path}`, { ...init, headers });
46
95
  };
47
96
 
48
- const response = await send(await this.auth.token());
97
+ const token = await this.auth.token();
98
+ const response = await send(token);
49
99
 
50
100
  if (response.status !== 401) return response;
51
101
  await response.body?.cancel();
52
102
 
53
- return send(await this.auth.refresh());
103
+ return send(await this.auth.refresh(token));
54
104
  }
55
105
 
56
106
  /** The API's JSON answer parsed with `schema`, or a WorkspaceError with its message. */
@@ -58,16 +108,24 @@ export class Workspace {
58
108
  path: string,
59
109
  schema: Schema,
60
110
  init: JsonRequest = {}
61
- ): Promise<z.output<Schema>> {
111
+ ) {
62
112
  return parse(await this.send(path, init), schema);
63
113
  }
64
114
 
65
115
  /** A request whose answer only needs to be a success; else a WorkspaceError. */
66
- async call(path: string, init: JsonRequest = {}): Promise<void> {
116
+ async call(path: string, init: JsonRequest = {}) {
67
117
  await parse(await this.send(path, init), z.unknown());
68
118
  }
69
119
 
70
120
  private send(path: string, init: JsonRequest) {
121
+ if (init.raw) {
122
+ return this.request(path, {
123
+ method: init.method ?? "POST",
124
+ headers: { "content-type": "application/octet-stream" },
125
+ body: init.raw,
126
+ });
127
+ }
128
+
71
129
  return this.request(path, {
72
130
  method: init.method ?? "GET",
73
131
  headers:
@@ -86,7 +144,8 @@ export class Workspace {
86
144
  /** A mailbox this sign-in may import into, by id or address. */
87
145
  async importTarget(idOrAddress: string) {
88
146
  const wanted = idOrAddress.trim().toLowerCase();
89
- const targets = await this.importTargets();
147
+ this.importMailboxes ??= await this.importTargets();
148
+ const targets = this.importMailboxes;
90
149
 
91
150
  const target = targets.find(
92
151
  (item) =>
@@ -105,10 +164,7 @@ export class Workspace {
105
164
  return target;
106
165
  }
107
166
 
108
- async importMessage(
109
- mailboxId: string,
110
- item: ImportItem
111
- ): Promise<ImportResult> {
167
+ async importMessage(mailboxId: string, item: ImportItem) {
112
168
  const query = new URLSearchParams({
113
169
  sourceId: item.sourceId,
114
170
  placement: item.placement,
@@ -160,7 +216,12 @@ export class Workspace {
160
216
  }
161
217
  }
162
218
 
163
- type JsonRequest = { method?: string; body?: unknown };
219
+ type JsonRequest = {
220
+ method?: string;
221
+ body?: unknown;
222
+ /** Bytes sent as they are, instead of a JSON `body`. */
223
+ raw?: Uint8Array<ArrayBuffer>;
224
+ };
164
225
 
165
226
  const importResponseSchema = z.object({
166
227
  duplicate: z.boolean(),
@@ -178,9 +239,11 @@ const errorSchema = z.object({
178
239
 
179
240
  type JsonValue = z.core.util.JSONType;
180
241
 
181
- function parseJson(text: string): JsonValue | undefined {
242
+ function parseJson(text: string) {
182
243
  try {
183
- return JSON.parse(text);
244
+ const value: JsonValue = JSON.parse(text);
245
+
246
+ return value;
184
247
  } catch {
185
248
  // Not JSON: a proxy's or the platform's error page.
186
249
  return undefined;
@@ -190,7 +253,7 @@ function parseJson(text: string): JsonValue | undefined {
190
253
  async function parse<Schema extends z.ZodType>(
191
254
  response: Response,
192
255
  schema: Schema
193
- ): Promise<z.output<Schema>> {
256
+ ) {
194
257
  const text = await response.text();
195
258
  const json = parseJson(text);
196
259
 
package/index.ts CHANGED
@@ -7,6 +7,9 @@ if (process.argv[2] === "module") {
7
7
  } else if (process.argv[2] === "import") {
8
8
  const { main } = await import("./import/cli.ts");
9
9
  process.exitCode = await main(process.argv.slice(3));
10
+ } else if (process.argv[2] === "restore-mx") {
11
+ const { main } = await import("./setup/mx-recovery.ts");
12
+ process.exitCode = await main(process.argv.slice(3));
10
13
  } else {
11
14
  const { main } = await import("./create.ts");
12
15
  process.exitCode = await main(process.argv.slice(2));
@@ -40,7 +40,7 @@ export type ModuleNames = {
40
40
  label: string;
41
41
  };
42
42
 
43
- export function moduleNames(name: string): ModuleNames {
43
+ export function moduleNames(name: string) {
44
44
  if (!MODULE_NAME.test(name)) {
45
45
  throw new Error(
46
46
  `"${name}" is not a module name: use lowercase letters, words joined by dashes (e.g. time-off)`
@@ -104,7 +104,7 @@ export const ${camel}WebhookEvents: Record<string, WebhookEventDeclaration> = {
104
104
  `,
105
105
  [`${dir}/worker/schema.ts`]: `import { sql } from "drizzle-orm";
106
106
  import { integer, sqliteTable, text } from "drizzle-orm/sqlite-core";
107
- import { users } from "@open-workspace/core/module";
107
+ import { users } from "@open-workspace/core/schema";
108
108
 
109
109
  /**
110
110
  * The module's D1 tables, next to core's in the workspace's database. After
@@ -150,7 +150,7 @@ const items = new Hono<AppEnv>()
150
150
  const user = c.get("user");
151
151
  const item = { id: createId("${snake.slice(0, 8)}"), title: c.req.valid("json").title };
152
152
  await createDb(c.env.DB).insert(${camel}Items).values({ ...item, authorUserId: user.id });
153
- deferWebhookTask((task) => c.executionCtx.waitUntil(task), (eventId) => queueWebhookEvent(c.env, {
153
+ deferWebhookTask((eventId) => queueWebhookEvent(c.env, {
154
154
  eventId,
155
155
  eventType: "${snake}.item_created",
156
156
  occurredAt: Date.now(),
@@ -187,14 +187,14 @@ import { ${constant}_MODULE, ${camel}OauthScopes, ${camel}WebhookEvents } from "
187
187
  import { ${camel}AccountApi } from "./routes";
188
188
 
189
189
  /** The module's Worker half; the generated Worker entry calls this factory (../index.ts). */
190
- export function ${camel}(): WorkspaceModule {
190
+ export function ${camel}() {
191
191
  return {
192
192
  name: ${constant}_MODULE,
193
193
  accountApi: ${camel}AccountApi,
194
194
  oauthScopes: ${camel}OauthScopes,
195
195
  webhookEvents: ${camel}WebhookEvents,
196
196
  mcpTools: () => import("./mcp").then((tools) => tools.register${pascal}Tools),
197
- };
197
+ } satisfies WorkspaceModule;
198
198
  }
199
199
  `,
200
200
  [`${dir}/index.ts`]: `// The module's server entry: its default export is the factory of its WorkspaceModule.
@@ -205,13 +205,13 @@ import type { WorkspaceModuleInfra } from "@open-workspace/core/alchemy";
205
205
  import { ${constant}_MODULE } from "./shared/module";
206
206
 
207
207
  /** The module's Alchemy half: \`OpenWorkspace({ modules: [${pascal}()] })\`. */
208
- export function ${pascal}(): WorkspaceModuleInfra {
208
+ export function ${pascal}() {
209
209
  return {
210
210
  name: ${constant}_MODULE,
211
211
  server: { entry: join(import.meta.dirname, "index.ts") },
212
212
  migrations: join(import.meta.dirname, "migrations"),
213
213
  client: { entry: join(import.meta.dirname, "src", "client.tsx") },
214
- };
214
+ } satisfies WorkspaceModuleInfra;
215
215
  }
216
216
  `,
217
217
  [`${dir}/src/client.tsx`]: `import { Boxes } from "lucide-react";
@@ -303,7 +303,7 @@ export default defineConfig({
303
303
  {
304
304
  compilerOptions: {
305
305
  target: "ES2023",
306
- lib: ["ES2023", "DOM", "DOM.Iterable"],
306
+ lib: ["ES2023", "ESNext.TypedArrays", "DOM", "DOM.Iterable"],
307
307
  module: "ESNext",
308
308
  moduleResolution: "Bundler",
309
309
  jsx: "react-jsx",
@@ -336,10 +336,7 @@ export function wiringLines(names: ModuleNames) {
336
336
  * when that cannot be done safely: no single `modules: [...]` on one line.
337
337
  * An already wired file comes back unchanged.
338
338
  */
339
- export function wireAlchemyRun(
340
- source: string,
341
- names: ModuleNames
342
- ): string | null {
339
+ export function wireAlchemyRun(source: string, names: ModuleNames) {
343
340
  const { importLine, entry } = wiringLines(names);
344
341
 
345
342
  if (source.includes(importLine)) return source;
package/module.ts CHANGED
@@ -14,11 +14,7 @@ import {
14
14
  * writes `modules/<name>/` and wires it into `alchemy.run.ts`. Returns the
15
15
  * exit code.
16
16
  */
17
- export function main(
18
- args: string[],
19
- cwd = process.cwd(),
20
- log = console.log
21
- ): number {
17
+ export function main(args: string[], cwd = process.cwd(), log = console.log) {
22
18
  const [name] = args;
23
19
 
24
20
  if (!name || args.length > 1) {