devflare 1.0.0-next.39 → 1.0.0-next.40

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 (277) hide show
  1. package/dist/_chunks/account-BtWcv3X9.js +462 -0
  2. package/dist/_chunks/account-resources-CsmVowJp.js +159 -0
  3. package/dist/_chunks/ai-CBEuLdoP.js +322 -0
  4. package/dist/_chunks/api-TzdliH-6.js +568 -0
  5. package/dist/_chunks/build-3T6O4uIg.js +24 -0
  6. package/dist/_chunks/build-artifacts-8TqBSQkG.js +483 -0
  7. package/dist/_chunks/cli-BTF1X4SG.js +1128 -0
  8. package/dist/_chunks/cloudflare-BaloqI3H.js +157 -0
  9. package/dist/_chunks/colors-DiK6wPJ5.js +13 -0
  10. package/dist/_chunks/command-utils-BsfkmTqh.js +45 -0
  11. package/dist/_chunks/compiler-uoyAQ8zW.js +424 -0
  12. package/dist/_chunks/config-D5u-bEkn.js +78 -0
  13. package/dist/_chunks/config-path-DCPto4XB.js +42 -0
  14. package/dist/_chunks/context-CX50Y2Kb.js +2250 -0
  15. package/dist/_chunks/decorators-QmV57ixr.js +19 -0
  16. package/dist/_chunks/dependencies-C2oxFjU_.js +57 -0
  17. package/dist/_chunks/deploy-DMTr6JeR.js +915 -0
  18. package/dist/_chunks/dev-CvRHmRFZ.js +3456 -0
  19. package/dist/_chunks/doctor-DIG8DoFU.js +219 -0
  20. package/dist/_chunks/durable-object-DMtH0XYX.js +234 -0
  21. package/dist/_chunks/env-S0_nMVz1.js +125 -0
  22. package/dist/_chunks/family-DXC5SdFK.js +143 -0
  23. package/dist/_chunks/generated-artifacts-dMJY4KAt.js +32 -0
  24. package/dist/_chunks/glob-CmQOvunB.js +56 -0
  25. package/dist/_chunks/init-3moXTgpb.js +165 -0
  26. package/dist/_chunks/loader-DLXO60RO.js +1153 -0
  27. package/dist/_chunks/local-dev-vars-CTSa-wvF.js +81 -0
  28. package/dist/_chunks/local-hyperdrive-CJ90j46O.js +119 -0
  29. package/dist/_chunks/local-media-bindings-DsAW4AMF.js +335 -0
  30. package/dist/_chunks/local-secrets-DMmEOygL.js +123 -0
  31. package/dist/_chunks/local-workflow-entrypoints-Wip3o1u8.js +90 -0
  32. package/dist/_chunks/login-BmnDzDlH.js +51 -0
  33. package/dist/_chunks/package-metadata-DAuCkyvK.js +39 -0
  34. package/dist/_chunks/preferences-BKp_7XJx.js +241 -0
  35. package/dist/_chunks/preview-BhqDmq8I.js +456 -0
  36. package/dist/_chunks/preview-registry-ClAbLTHH.js +1186 -0
  37. package/dist/_chunks/preview-resources-DdXj8LMM.js +358 -0
  38. package/dist/_chunks/previews-Dlr13x5M.js +1134 -0
  39. package/dist/_chunks/productions-D3AnOHac.js +411 -0
  40. package/dist/_chunks/ref-CYJNAAe_.js +178 -0
  41. package/dist/_chunks/remote-CZnP-HLJ.js +79 -0
  42. package/dist/_chunks/remote-config-D39BY9ji.js +132 -0
  43. package/dist/_chunks/resolve-package-Y84HB3Nt.js +133 -0
  44. package/dist/_chunks/rolldown-runtime-CvQ6eiug.js +14 -0
  45. package/dist/_chunks/routes-C3FqES2W.js +796 -0
  46. package/dist/_chunks/runtime-FvXvfuZ2.js +550 -0
  47. package/dist/_chunks/schema-normalization-DWVleVxo.js +477 -0
  48. package/dist/_chunks/secrets-70eN0Q6C.js +95 -0
  49. package/dist/_chunks/token-kguIDmej.js +333 -0
  50. package/dist/_chunks/tokens-iVcgNXi-.js +221 -0
  51. package/dist/_chunks/types-OrLbzv4I.js +476 -0
  52. package/dist/_chunks/ui-BUoZApvE.js +103 -0
  53. package/dist/_chunks/usage-BBTGzjon.js +272 -0
  54. package/dist/_chunks/vite-CsI0E-uV.js +1235 -0
  55. package/dist/_chunks/vite-utils-OVLMV605.js +183 -0
  56. package/dist/_chunks/worker-CS1jgNFE.js +410 -0
  57. package/dist/_chunks/worker-bundler-dTTnYU3n.js +458 -0
  58. package/dist/_chunks/worker-entrypoint-CQW77lG8.js +247 -0
  59. package/dist/_chunks/workerName-CFJsLZA-.js +23 -0
  60. package/dist/bridge/index.d.ts +6 -6
  61. package/dist/bridge/miniflare.d.ts +2 -2
  62. package/dist/bridge/proxy.d.ts +1 -1
  63. package/dist/bridge/v2/body-streams.d.ts +1 -1
  64. package/dist/bridge/v2/codec.d.ts +4 -4
  65. package/dist/bridge/v2/index.d.ts +10 -10
  66. package/dist/bridge/v2/serialization.d.ts +1 -1
  67. package/dist/bridge/v2/value-codec.d.ts +1 -1
  68. package/dist/bridge/v2/value-serialization.d.ts.map +1 -1
  69. package/dist/bridge/v2/ws-relay.d.ts +3 -3
  70. package/dist/browser-shim/index.d.ts +2 -2
  71. package/dist/browser.d.ts +70 -70
  72. package/dist/browser.js +74 -2462
  73. package/dist/bundler/do-bundler.d.ts +1 -1
  74. package/dist/bundler/index.d.ts +3 -3
  75. package/dist/bundler/rolldown-shared.d.ts +1 -1
  76. package/dist/bundler/worker-bundler.d.ts +1 -1
  77. package/dist/cli/build-manifest.d.ts +1 -1
  78. package/dist/cli/command-utils.d.ts +1 -1
  79. package/dist/cli/commands/account.d.ts +1 -1
  80. package/dist/cli/commands/ai.d.ts +1 -1
  81. package/dist/cli/commands/build-artifacts.d.ts +5 -5
  82. package/dist/cli/commands/build.d.ts +1 -1
  83. package/dist/cli/commands/config.d.ts +1 -1
  84. package/dist/cli/commands/deploy/prepare.d.ts +2 -2
  85. package/dist/cli/commands/deploy/runtime.d.ts +1 -1
  86. package/dist/cli/commands/deploy/verification.d.ts +1 -1
  87. package/dist/cli/commands/deploy.d.ts +1 -1
  88. package/dist/cli/commands/dev.d.ts +1 -1
  89. package/dist/cli/commands/doctor.d.ts +1 -1
  90. package/dist/cli/commands/init.d.ts +1 -1
  91. package/dist/cli/commands/login.d.ts +1 -1
  92. package/dist/cli/commands/previews-support/cleanup.d.ts +1 -1
  93. package/dist/cli/commands/previews-support/family.d.ts +3 -3
  94. package/dist/cli/commands/previews-support/render.d.ts +3 -3
  95. package/dist/cli/commands/previews-support/theme.d.ts +2 -2
  96. package/dist/cli/commands/previews-support/types.d.ts +2 -2
  97. package/dist/cli/commands/previews.d.ts +1 -1
  98. package/dist/cli/commands/productions.d.ts +1 -1
  99. package/dist/cli/commands/remote.d.ts +1 -1
  100. package/dist/cli/commands/secrets.d.ts +1 -1
  101. package/dist/cli/commands/token.d.ts +1 -1
  102. package/dist/cli/commands/type-generation/discovery.d.ts +2 -2
  103. package/dist/cli/commands/type-generation/generator.d.ts +3 -3
  104. package/dist/cli/commands/type-generation/models.d.ts +1 -1
  105. package/dist/cli/commands/types.d.ts +1 -1
  106. package/dist/cli/commands/worker.d.ts +1 -1
  107. package/dist/cli/deploy-strategy.d.ts +1 -1
  108. package/dist/cli/deploy-target.d.ts +1 -1
  109. package/dist/cli/help-pages/pages/account.d.ts +1 -1
  110. package/dist/cli/help-pages/pages/core.d.ts +1 -1
  111. package/dist/cli/help-pages/pages/index.d.ts +1 -1
  112. package/dist/cli/help-pages/pages/misc.d.ts +1 -1
  113. package/dist/cli/help-pages/pages/previews.d.ts +1 -1
  114. package/dist/cli/help-pages/pages/productions.d.ts +1 -1
  115. package/dist/cli/help-pages/render.d.ts +2 -2
  116. package/dist/cli/help-pages/shared.d.ts +1 -1
  117. package/dist/cli/help.d.ts +2 -2
  118. package/dist/cli/index.js +2 -1383
  119. package/dist/cli/preview-bindings.d.ts +3 -3
  120. package/dist/cli/preview.d.ts +1 -1
  121. package/dist/cli/wrangler-auth.d.ts +1 -1
  122. package/dist/cloudflare/account-core.d.ts +2 -2
  123. package/dist/cloudflare/account-resources.d.ts +2 -2
  124. package/dist/cloudflare/account-status.d.ts +1 -1
  125. package/dist/cloudflare/account-workers.d.ts +2 -2
  126. package/dist/cloudflare/account.d.ts +7 -7
  127. package/dist/cloudflare/auth.d.ts +1 -1
  128. package/dist/cloudflare/index.d.ts +13 -13
  129. package/dist/cloudflare/index.js +4 -59
  130. package/dist/cloudflare/kv-namespace.d.ts +1 -1
  131. package/dist/cloudflare/preview-registry-cache.d.ts +1 -1
  132. package/dist/cloudflare/preview-registry-inference.d.ts +2 -2
  133. package/dist/cloudflare/preview-registry-records.d.ts +3 -3
  134. package/dist/cloudflare/preview-registry-shape.d.ts +2 -2
  135. package/dist/cloudflare/preview-registry-store.d.ts +3 -3
  136. package/dist/cloudflare/preview-registry-transport.d.ts +2 -2
  137. package/dist/cloudflare/preview-registry-types.d.ts +2 -2
  138. package/dist/cloudflare/preview-registry.d.ts +5 -5
  139. package/dist/cloudflare/tokens.d.ts +2 -2
  140. package/dist/cloudflare/usage.d.ts +2 -2
  141. package/dist/config/binding-resolution-helpers.d.ts +1 -1
  142. package/dist/config/compiler/bindings.d.ts +2 -2
  143. package/dist/config/compiler/core-helpers.d.ts +2 -2
  144. package/dist/config/compiler/do-workers.d.ts +2 -2
  145. package/dist/config/compiler/paths.d.ts +1 -1
  146. package/dist/config/compiler.d.ts +6 -6
  147. package/dist/config/define.d.ts +2 -2
  148. package/dist/config/deploy-resources.d.ts +5 -5
  149. package/dist/config/env-vars.d.ts +1 -1
  150. package/dist/config/framework-providers.d.ts +1 -1
  151. package/dist/config/index.d.ts +12 -12
  152. package/dist/config/loader.d.ts +2 -2
  153. package/dist/config/local-dev-vars.d.ts +1 -1
  154. package/dist/config/preview-resources.d.ts +4 -4
  155. package/dist/config/preview.d.ts +1 -1
  156. package/dist/config/ref.d.ts +2 -2
  157. package/dist/config/resolve-phased.d.ts +4 -4
  158. package/dist/config/resolve.d.ts +1 -1
  159. package/dist/config/resource-resolution.d.ts +6 -6
  160. package/dist/config/schema-env.d.ts +20 -20
  161. package/dist/config/schema-normalization.d.ts +1 -1
  162. package/dist/config/schema-types-bindings.d.ts +4 -4
  163. package/dist/config/schema-types-build.d.ts +1 -1
  164. package/dist/config/schema-types.d.ts +7 -7
  165. package/dist/config/schema.d.ts +46 -46
  166. package/dist/config/service-bindings-validation.d.ts +1 -1
  167. package/dist/config-entry.d.ts +6 -6
  168. package/dist/config-entry.js +3 -8
  169. package/dist/decorators/index.d.ts +2 -2
  170. package/dist/decorators/index.js +2 -9
  171. package/dist/dev-server/d1-migrations.d.ts +1 -1
  172. package/dist/dev-server/dev-server-state.d.ts +6 -6
  173. package/dist/dev-server/gateway-script.d.ts +1 -1
  174. package/dist/dev-server/index.d.ts +1 -1
  175. package/dist/dev-server/miniflare-bindings.d.ts +1 -1
  176. package/dist/dev-server/miniflare-dev-config.d.ts +5 -5
  177. package/dist/dev-server/miniflare-worker-config.d.ts +3 -3
  178. package/dist/dev-server/server-startup-helpers.d.ts +6 -6
  179. package/dist/dev-server/worker-surface-paths.d.ts +2 -2
  180. package/dist/index.d.ts +8 -8
  181. package/dist/index.js +9 -22
  182. package/dist/runtime/context-events.d.ts +1 -1
  183. package/dist/runtime/context.d.ts +3 -3
  184. package/dist/runtime/exports.d.ts +2 -2
  185. package/dist/runtime/index.d.ts +10 -10
  186. package/dist/runtime/index.js +5 -57
  187. package/dist/runtime/middleware.d.ts +1 -1
  188. package/dist/runtime/router/index.d.ts +3 -3
  189. package/dist/runtime/validation.d.ts +1 -1
  190. package/dist/secrets/local-secrets.d.ts +1 -1
  191. package/dist/shims/local-media-bindings.d.ts +1 -1
  192. package/dist/sveltekit/index.d.ts +1 -1
  193. package/dist/sveltekit/index.js +327 -9
  194. package/dist/sveltekit/local-bindings.d.ts +1 -1
  195. package/dist/sveltekit/platform.d.ts +1 -1
  196. package/dist/test/binding-hints.d.ts +2 -2
  197. package/dist/test/cf.d.ts +19 -19
  198. package/dist/test/index.d.ts +18 -18
  199. package/dist/test/index.js +4495 -46
  200. package/dist/test/offline-bindings.d.ts +3 -3
  201. package/dist/test/resolve-service-bindings.d.ts +1 -1
  202. package/dist/test/simple-context-bindings.d.ts +1 -1
  203. package/dist/test/simple-context-durable-objects.d.ts +1 -1
  204. package/dist/test/simple-context-env.d.ts +2 -2
  205. package/dist/test/simple-context-handlers.d.ts +2 -2
  206. package/dist/test/simple-context-lifecycle.d.ts +2 -2
  207. package/dist/test/simple-context-mfconfig.d.ts +1 -1
  208. package/dist/test/simple-context-multi-worker.d.ts +2 -2
  209. package/dist/test/simple-context-runtime.d.ts +1 -1
  210. package/dist/test/simple-context-startup.d.ts +1 -1
  211. package/dist/test/simple-context.d.ts +1 -1
  212. package/dist/test/utilities/env.d.ts +3 -3
  213. package/dist/test/utilities.d.ts +10 -10
  214. package/dist/test/worker.d.ts +1 -1
  215. package/dist/transform/index.d.ts +2 -2
  216. package/dist/utils/send-email.js +163 -19
  217. package/dist/vite/config-file.d.ts +2 -2
  218. package/dist/vite/index.d.ts +3 -3
  219. package/dist/vite/index.js +2 -31
  220. package/dist/vite/plugin-config-hook.d.ts +1 -1
  221. package/dist/vite/plugin-context.d.ts +3 -3
  222. package/dist/vite/plugin-durable-objects.d.ts +2 -2
  223. package/dist/vite/plugin-programmatic.d.ts +1 -1
  224. package/dist/vite/plugin-service-bindings.d.ts +2 -2
  225. package/dist/vite/plugin.d.ts +3 -3
  226. package/dist/worker-entry/composed-worker.d.ts +1 -1
  227. package/dist/worker-entry/routes.d.ts +2 -2
  228. package/dist/worker-entry/surface-paths.d.ts +1 -1
  229. package/dist/workflows/local-workflow-entrypoints.d.ts +1 -1
  230. package/package.json +5 -3
  231. package/dist/account-4tgh03a8.js +0 -484
  232. package/dist/ai-r3zqmxan.js +0 -261
  233. package/dist/api-6z01z734.js +0 -33
  234. package/dist/build-kw625v84.js +0 -51
  235. package/dist/config-ghk2bxj3.js +0 -102
  236. package/dist/deploy-9kee65n9.js +0 -1062
  237. package/dist/dev-x8zr249a.js +0 -3569
  238. package/dist/doctor-0ng5qrr1.js +0 -258
  239. package/dist/durable-object-0ybmg08a.js +0 -13
  240. package/dist/index-04wh9bxx.js +0 -514
  241. package/dist/index-0cc05hzv.js +0 -74
  242. package/dist/index-2yv7w548.js +0 -185
  243. package/dist/index-37x76zdn.js +0 -4
  244. package/dist/index-3cpzsr47.js +0 -125
  245. package/dist/index-3t6rypgc.js +0 -13
  246. package/dist/index-4mmpccrb.js +0 -309
  247. package/dist/index-5dkjffqz.js +0 -25
  248. package/dist/index-5hy7jmv3.js +0 -890
  249. package/dist/index-627srx16.js +0 -45
  250. package/dist/index-7m557715.js +0 -283
  251. package/dist/index-a8pnvg3r.js +0 -52
  252. package/dist/index-aabgympv.js +0 -39
  253. package/dist/index-atwc3csp.js +0 -256
  254. package/dist/index-cv4cvrxe.js +0 -2046
  255. package/dist/index-h7r11y4a.js +0 -539
  256. package/dist/index-hvtd936d.js +0 -1229
  257. package/dist/index-kcp7y951.js +0 -136
  258. package/dist/index-maw0jjnn.js +0 -147
  259. package/dist/index-mek9msfv.js +0 -705
  260. package/dist/index-n4xkaymm.js +0 -236
  261. package/dist/index-nkk59p3y.js +0 -579
  262. package/dist/index-phcrvs6d.js +0 -342
  263. package/dist/index-se4kw8tm.js +0 -460
  264. package/dist/index-x8s9rwfh.js +0 -2020
  265. package/dist/index-y7w3x9p1.js +0 -18
  266. package/dist/index-z9gy8w6b.js +0 -57
  267. package/dist/index-zdd0d9qa.js +0 -199
  268. package/dist/init-tb8jqgvr.js +0 -180
  269. package/dist/login-4h1sfsed.js +0 -75
  270. package/dist/previews-qr7c5j8h.js +0 -1336
  271. package/dist/productions-xpmd6bw8.js +0 -505
  272. package/dist/remote-kqcvhnfx.js +0 -192
  273. package/dist/secrets-6wbdsdek.js +0 -89
  274. package/dist/token-yp1qa70y.js +0 -419
  275. package/dist/types-15yv4cj3.js +0 -701
  276. package/dist/worker-1yg72jxg.js +0 -510
  277. package/dist/worker-entrypoint-y8s9kdcx.js +0 -15
@@ -1,890 +0,0 @@
1
- import {
2
- discoverDurableObjectFiles
3
- } from "./index-cv4cvrxe.js";
4
- import {
5
- findFiles
6
- } from "./index-5dkjffqz.js";
7
- import {
8
- transformDurableObject
9
- } from "./index-4mmpccrb.js";
10
- import {
11
- __require
12
- } from "./index-37x76zdn.js";
13
-
14
- // src/bundler/worker-bundler.ts
15
- import { fileURLToPath } from "node:url";
16
- import { dirname, resolve as resolve2 } from "pathe";
17
-
18
- // src/bundler/defaults.ts
19
- function createWorkerdBundlerDefaults() {
20
- return {
21
- platform: "browser",
22
- defaultTsconfigMode: "if-present",
23
- sourcemap: false,
24
- minify: false
25
- };
26
- }
27
-
28
- // src/bundler/rolldown-shared.ts
29
- import { existsSync } from "node:fs";
30
- import { resolve } from "pathe";
31
-
32
- // src/bundler/worker-compat.ts
33
- import MagicString from "magic-string";
34
- import ts from "typescript";
35
- var WORKER_DYNAMIC_IMPORT_ERROR = "Devflare worker bundles cannot contain unresolved dynamic import() expressions because Miniflare/workerd reject dynamic module specifiers";
36
- function getScriptKind(id) {
37
- if (id.endsWith(".tsx")) {
38
- return ts.ScriptKind.TSX;
39
- }
40
- if (id.endsWith(".ts") || id.endsWith(".mts") || id.endsWith(".cts")) {
41
- return ts.ScriptKind.TS;
42
- }
43
- if (id.endsWith(".jsx")) {
44
- return ts.ScriptKind.JSX;
45
- }
46
- return ts.ScriptKind.JS;
47
- }
48
- function createSourceFile(code, id) {
49
- return ts.createSourceFile(id, code, ts.ScriptTarget.Latest, true, getScriptKind(id));
50
- }
51
- function hasExportModifier(node) {
52
- if (!ts.canHaveModifiers(node)) {
53
- return false;
54
- }
55
- return ts.getModifiers(node)?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword) ?? false;
56
- }
57
- function isConstVariableStatement(statement) {
58
- return ts.isVariableStatement(statement) && (statement.declarationList.flags & ts.NodeFlags.Const) !== 0;
59
- }
60
- function quoteString(value) {
61
- return `'${value.replace(/\\/g, "\\\\").replace(/'/g, `\\'`)}'`;
62
- }
63
- function resolveLiteralImportSpecifier(expression, constStrings) {
64
- if (ts.isStringLiteral(expression) || ts.isNoSubstitutionTemplateLiteral(expression)) {
65
- return expression.text;
66
- }
67
- if (ts.isParenthesizedExpression(expression)) {
68
- return resolveLiteralImportSpecifier(expression.expression, constStrings);
69
- }
70
- if (ts.isIdentifier(expression)) {
71
- return constStrings.get(expression.text) ?? null;
72
- }
73
- return null;
74
- }
75
- function collectTopLevelConstStrings(sourceFile) {
76
- const constStrings = new Map;
77
- for (const statement of sourceFile.statements) {
78
- if (!isConstVariableStatement(statement)) {
79
- continue;
80
- }
81
- for (const declaration of statement.declarationList.declarations) {
82
- if (!ts.isIdentifier(declaration.name) || !declaration.initializer) {
83
- continue;
84
- }
85
- const literal = resolveLiteralImportSpecifier(declaration.initializer, constStrings);
86
- if (literal !== null) {
87
- constStrings.set(declaration.name.text, literal);
88
- }
89
- }
90
- }
91
- return constStrings;
92
- }
93
- function unwrapDynamicImportExpression(expression) {
94
- if (ts.isParenthesizedExpression(expression)) {
95
- return unwrapDynamicImportExpression(expression.expression);
96
- }
97
- if (ts.isAwaitExpression(expression)) {
98
- return unwrapDynamicImportExpression(expression.expression);
99
- }
100
- if (!ts.isCallExpression(expression) || expression.expression.kind !== ts.SyntaxKind.ImportKeyword) {
101
- return null;
102
- }
103
- return expression;
104
- }
105
- function getWrapperBodyExpression(body) {
106
- if (!body) {
107
- return null;
108
- }
109
- if (!ts.isBlock(body)) {
110
- return body;
111
- }
112
- if (body.statements.length !== 1) {
113
- return null;
114
- }
115
- const [statement] = body.statements;
116
- if (!ts.isReturnStatement(statement) || !statement.expression) {
117
- return null;
118
- }
119
- return statement.expression;
120
- }
121
- function createImportWrapper(name, parameterName, body, sourceFile) {
122
- const bodyExpression = getWrapperBodyExpression(body);
123
- if (!bodyExpression) {
124
- return null;
125
- }
126
- const importExpression = unwrapDynamicImportExpression(bodyExpression);
127
- if (!importExpression || importExpression.arguments.length < 1) {
128
- return null;
129
- }
130
- const [importArgument] = importExpression.arguments;
131
- if (!ts.isIdentifier(importArgument) || importArgument.text !== parameterName || !body) {
132
- return null;
133
- }
134
- return {
135
- name,
136
- parameterName,
137
- bodyStart: body.getStart(sourceFile),
138
- bodyEnd: body.getEnd(),
139
- specifiers: new Set,
140
- hasUnsupportedCalls: false
141
- };
142
- }
143
- function collectImportWrappers(sourceFile) {
144
- const wrappers = new Map;
145
- for (const statement of sourceFile.statements) {
146
- if (ts.isFunctionDeclaration(statement) && statement.name && !hasExportModifier(statement) && statement.parameters.length === 1 && ts.isIdentifier(statement.parameters[0]?.name)) {
147
- const wrapper = createImportWrapper(statement.name.text, statement.parameters[0].name.text, statement.body, sourceFile);
148
- if (wrapper) {
149
- wrappers.set(wrapper.name, wrapper);
150
- }
151
- }
152
- if (!isConstVariableStatement(statement) || hasExportModifier(statement)) {
153
- continue;
154
- }
155
- for (const declaration of statement.declarationList.declarations) {
156
- if (!ts.isIdentifier(declaration.name) || !declaration.initializer) {
157
- continue;
158
- }
159
- if (!ts.isArrowFunction(declaration.initializer) && !ts.isFunctionExpression(declaration.initializer)) {
160
- continue;
161
- }
162
- if (declaration.initializer.parameters.length !== 1 || !ts.isIdentifier(declaration.initializer.parameters[0]?.name)) {
163
- continue;
164
- }
165
- const wrapper = createImportWrapper(declaration.name.text, declaration.initializer.parameters[0].name.text, declaration.initializer.body, sourceFile);
166
- if (wrapper) {
167
- wrappers.set(wrapper.name, wrapper);
168
- }
169
- }
170
- }
171
- return wrappers;
172
- }
173
- function collectWrapperCallSpecifiers(sourceFile, wrappers, constStrings) {
174
- function visit(node) {
175
- if (ts.isCallExpression(node) && ts.isIdentifier(node.expression)) {
176
- const wrapper = wrappers.get(node.expression.text);
177
- if (wrapper) {
178
- if (node.arguments.length !== 1) {
179
- wrapper.hasUnsupportedCalls = true;
180
- } else {
181
- const specifier = resolveLiteralImportSpecifier(node.arguments[0], constStrings);
182
- if (specifier === null) {
183
- wrapper.hasUnsupportedCalls = true;
184
- } else {
185
- wrapper.specifiers.add(specifier);
186
- }
187
- }
188
- }
189
- }
190
- ts.forEachChild(node, visit);
191
- }
192
- visit(sourceFile);
193
- }
194
- function createImportIdentifier(specifierToIdentifier, specifier) {
195
- const existing = specifierToIdentifier.get(specifier);
196
- if (existing) {
197
- return existing;
198
- }
199
- const identifier = `__devflareDynamicImport${specifierToIdentifier.size}`;
200
- specifierToIdentifier.set(specifier, identifier);
201
- return identifier;
202
- }
203
- function buildWrapperBody(wrapper, specifierToIdentifier) {
204
- const cases = Array.from(wrapper.specifiers).sort((left, right) => left.localeCompare(right)).map((specifier) => {
205
- const identifier = createImportIdentifier(specifierToIdentifier, specifier);
206
- return ` case ${quoteString(specifier)}:
207
- return Promise.resolve(${identifier})`;
208
- }).join(`
209
- `);
210
- return `{
211
- switch (${wrapper.parameterName}) {
212
- ${cases}
213
- default:
214
- return Promise.reject(new Error(\`Unsupported dynamic import in Devflare worker bundle: \${${wrapper.parameterName}}\`))
215
- }
216
- }`;
217
- }
218
- function findContainingWrapper(callExpression, wrappers, sourceFile) {
219
- const start = callExpression.getStart(sourceFile);
220
- const end = callExpression.getEnd();
221
- for (const wrapper of wrappers) {
222
- if (start >= wrapper.bodyStart && end <= wrapper.bodyEnd) {
223
- return wrapper;
224
- }
225
- }
226
- return null;
227
- }
228
- function transformWorkerDynamicImports(code, id) {
229
- const sourceFile = createSourceFile(code, id);
230
- const constStrings = collectTopLevelConstStrings(sourceFile);
231
- const wrappers = collectImportWrappers(sourceFile);
232
- collectWrapperCallSpecifiers(sourceFile, wrappers, constStrings);
233
- const transformableWrappers = Array.from(wrappers.values()).filter((wrapper) => {
234
- return !wrapper.hasUnsupportedCalls && wrapper.specifiers.size > 0;
235
- });
236
- const replacements = [];
237
- const specifierToIdentifier = new Map;
238
- function visit(node) {
239
- if (ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword) {
240
- const containingWrapper = findContainingWrapper(node, transformableWrappers, sourceFile);
241
- if (containingWrapper && node.arguments.length === 1 && ts.isIdentifier(node.arguments[0]) && node.arguments[0].text === containingWrapper.parameterName) {
242
- return;
243
- }
244
- const [argument] = node.arguments;
245
- if (!argument) {
246
- return;
247
- }
248
- const specifier = resolveLiteralImportSpecifier(argument, constStrings);
249
- if (specifier !== null) {
250
- replacements.push({
251
- start: node.getStart(sourceFile),
252
- end: node.getEnd(),
253
- text: `Promise.resolve(${createImportIdentifier(specifierToIdentifier, specifier)})`
254
- });
255
- }
256
- }
257
- ts.forEachChild(node, visit);
258
- }
259
- visit(sourceFile);
260
- if (replacements.length === 0 && transformableWrappers.length === 0) {
261
- return null;
262
- }
263
- const s = new MagicString(code);
264
- for (const replacement of replacements.sort((left, right) => right.start - left.start)) {
265
- s.overwrite(replacement.start, replacement.end, replacement.text);
266
- }
267
- for (const wrapper of transformableWrappers.sort((left, right) => right.bodyStart - left.bodyStart)) {
268
- s.overwrite(wrapper.bodyStart, wrapper.bodyEnd, buildWrapperBody(wrapper, specifierToIdentifier));
269
- }
270
- if (specifierToIdentifier.size > 0) {
271
- const importBlock = Array.from(specifierToIdentifier.entries()).map(([specifier, identifier]) => `import * as ${identifier} from ${quoteString(specifier)}`).join(`
272
- `);
273
- if (code.startsWith("#!")) {
274
- const newlineIndex = code.indexOf(`
275
- `);
276
- if (newlineIndex === -1) {
277
- s.appendRight(code.length, `
278
- ${importBlock}
279
- `);
280
- } else {
281
- s.appendLeft(newlineIndex + 1, `${importBlock}
282
- `);
283
- }
284
- } else {
285
- s.appendLeft(0, `${importBlock}
286
- `);
287
- }
288
- }
289
- return {
290
- code: s.toString(),
291
- map: s.generateMap({
292
- source: id,
293
- file: `${id}.map`,
294
- includeContent: true
295
- })
296
- };
297
- }
298
- function findDynamicImportCalls(sourceFile) {
299
- const calls = [];
300
- function visit(node) {
301
- if (ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword) {
302
- calls.push(node);
303
- }
304
- ts.forEachChild(node, visit);
305
- }
306
- visit(sourceFile);
307
- return calls;
308
- }
309
- async function assertWorkerBundleHasNoDynamicImports(bundlePath) {
310
- const fs = await import("node:fs/promises");
311
- const code = await fs.readFile(bundlePath, "utf-8");
312
- const sourceFile = createSourceFile(code, bundlePath);
313
- const dynamicImports = findDynamicImportCalls(sourceFile);
314
- if (dynamicImports.length === 0) {
315
- return;
316
- }
317
- const examples = dynamicImports.slice(0, 3).map((callExpression) => {
318
- const start = callExpression.getStart(sourceFile);
319
- const { line, character } = sourceFile.getLineAndCharacterOfPosition(start);
320
- const snippet = code.slice(start, callExpression.getEnd()).replace(/\s+/g, " ").trim();
321
- return `- ${line + 1}:${character + 1} ${snippet}`;
322
- }).join(`
323
- `);
324
- throw new Error([
325
- WORKER_DYNAMIC_IMPORT_ERROR,
326
- `Bundle: ${bundlePath}`,
327
- `Examples:
328
- ${examples}`,
329
- "Devflare can normalize literal import() calls and simple helper wrappers whose call sites are literal strings, but truly runtime-computed specifiers must be converted to static imports for worker bundles."
330
- ].join(`
331
-
332
- `));
333
- }
334
- function createWorkerDynamicImportPlugin() {
335
- return {
336
- name: "devflare-worker-dynamic-imports",
337
- transform(code, id) {
338
- const result = transformWorkerDynamicImports(code, id);
339
- return result ?? null;
340
- }
341
- };
342
- }
343
-
344
- // src/bundler/rolldown-shared.ts
345
- var DEFAULT_EXTERNAL_MODULES = [
346
- /^cloudflare:/,
347
- /^node:/,
348
- "buffer",
349
- "crypto",
350
- "events",
351
- "http",
352
- "https",
353
- "net",
354
- "os",
355
- "path",
356
- "stream",
357
- "tls",
358
- "url",
359
- "util",
360
- "zlib",
361
- "fs",
362
- "child_process",
363
- "async_hooks",
364
- "querystring",
365
- "string_decoder",
366
- "assert",
367
- "dns"
368
- ];
369
- function toArray(value) {
370
- return Array.isArray(value) ? value : [value];
371
- }
372
- function matchesExternalPattern(pattern, id) {
373
- if (pattern instanceof RegExp) {
374
- pattern.lastIndex = 0;
375
- return pattern.test(id);
376
- }
377
- return pattern === id;
378
- }
379
- function matchesExternalOption(option, id, parentId, isResolved) {
380
- if (!option) {
381
- return false;
382
- }
383
- if (typeof option === "function") {
384
- return option(id, parentId, isResolved) ?? false;
385
- }
386
- return toArray(option).some((pattern) => matchesExternalPattern(pattern, id));
387
- }
388
- function mergeExternalOptions(base, user) {
389
- if (!base) {
390
- return user;
391
- }
392
- if (!user) {
393
- return base;
394
- }
395
- if (typeof base !== "function" && typeof user !== "function") {
396
- return [...toArray(base), ...toArray(user)];
397
- }
398
- return (id, parentId, isResolved) => {
399
- return matchesExternalOption(base, id, parentId, isResolved) || matchesExternalOption(user, id, parentId, isResolved) || false;
400
- };
401
- }
402
- function mergePluginOptions(base, user) {
403
- if (!base) {
404
- return user;
405
- }
406
- if (!user) {
407
- return base;
408
- }
409
- return [base, user];
410
- }
411
- function aliasKey(find) {
412
- return find instanceof RegExp ? `re:${find.source}:${find.flags}` : `str:${find}`;
413
- }
414
- function normalizeAliasEntries(input) {
415
- if (!input) {
416
- return [];
417
- }
418
- if (Array.isArray(input)) {
419
- return input.filter((entry) => {
420
- return Boolean(entry) && typeof entry.replacement === "string";
421
- });
422
- }
423
- return Object.entries(input).filter(([, replacement]) => typeof replacement === "string").map(([find, replacement]) => ({ find, replacement }));
424
- }
425
- function mergeAliases(userAliases, frameworkDefaults) {
426
- const userKeys = new Set(userAliases.map((entry) => aliasKey(entry.find)));
427
- const frameworkFiltered = frameworkDefaults.filter((entry) => {
428
- return !userKeys.has(aliasKey(entry.find));
429
- });
430
- const seenUserKeys = new Set;
431
- const dedupedUser = [];
432
- for (let index = userAliases.length - 1;index >= 0; index--) {
433
- const entry = userAliases[index];
434
- const key = aliasKey(entry.find);
435
- if (seenUserKeys.has(key)) {
436
- continue;
437
- }
438
- seenUserKeys.add(key);
439
- dedupedUser.unshift(entry);
440
- }
441
- return [...frameworkFiltered, ...dedupedUser];
442
- }
443
- function aliasEntriesToRolldownRecord(entries) {
444
- const record = {};
445
- for (const entry of entries) {
446
- if (entry.find instanceof RegExp) {
447
- continue;
448
- }
449
- record[entry.find] = entry.replacement;
450
- }
451
- return record;
452
- }
453
- function mergeResolveOptions(base, user) {
454
- if (!base && !user) {
455
- return;
456
- }
457
- const frameworkEntries = normalizeAliasEntries(base?.alias);
458
- const userEntries = normalizeAliasEntries(user?.alias);
459
- const mergedEntries = mergeAliases(userEntries, frameworkEntries);
460
- const mergedAlias = aliasEntriesToRolldownRecord(mergedEntries);
461
- return {
462
- ...user ?? {},
463
- ...base ?? {},
464
- ...mergedEntries.length > 0 ? { alias: mergedAlias } : {}
465
- };
466
- }
467
- function resolveTsconfigOption(options) {
468
- if (options.userTsconfig) {
469
- return { tsconfig: options.userTsconfig };
470
- }
471
- const defaultTsconfigPath = resolve(options.cwd, "tsconfig.json");
472
- if (options.defaultMode === "always" || existsSync(defaultTsconfigPath)) {
473
- return { tsconfig: defaultTsconfigPath };
474
- }
475
- return {};
476
- }
477
- async function ensureDebugShim(outDir) {
478
- const fs = await import("node:fs/promises");
479
- const debugShimCode = `
480
- // Debug module shim for local development
481
- const createDebug = (namespace) => {
482
- const logger = (...args) => {
483
- if (createDebug.enabled) console.debug(\`[\${namespace}]\`, ...args)
484
- }
485
- logger.enabled = false
486
- logger.namespace = namespace
487
- logger.extend = (sub) => createDebug(\`\${namespace}:\${sub}\`)
488
- return logger
489
- }
490
- createDebug.enabled = false
491
- createDebug.formatters = {}
492
- export default createDebug
493
- `;
494
- const debugShimPath = resolve(outDir, "_debug_shim.js");
495
- await fs.writeFile(debugShimPath, debugShimCode, "utf-8");
496
- return debugShimPath;
497
- }
498
- function resolveWorkerCompatibleRolldownConfig(options) {
499
- const {
500
- output: userOutputOptions,
501
- input: _ignoredInput,
502
- cwd: _ignoredCwd,
503
- platform: _ignoredPlatform,
504
- target: _ignoredTarget,
505
- watch: _ignoredWatch,
506
- external: userExternal,
507
- plugins: userPlugins,
508
- resolve: userResolve,
509
- tsconfig: userTsconfig,
510
- ...userInputOptions
511
- } = options.rolldownOptions ?? {};
512
- const {
513
- codeSplitting: _ignoredCodeSplitting,
514
- dir: _ignoredDir,
515
- file: _ignoredFile,
516
- format: _ignoredFormat,
517
- inlineDynamicImports: _ignoredInlineDynamicImports,
518
- ...safeUserOutputOptions
519
- } = userOutputOptions ?? {};
520
- return {
521
- inputOptions: {
522
- ...userInputOptions,
523
- input: options.inputFile,
524
- cwd: options.cwd,
525
- platform: options.platform,
526
- ...resolveTsconfigOption({
527
- cwd: options.cwd,
528
- userTsconfig,
529
- defaultMode: options.defaultTsconfigMode
530
- }),
531
- external: mergeExternalOptions(DEFAULT_EXTERNAL_MODULES, userExternal),
532
- plugins: mergePluginOptions(createWorkerDynamicImportPlugin(), userPlugins),
533
- resolve: mergeResolveOptions(options.alias ? {
534
- alias: options.alias
535
- } : undefined, userResolve)
536
- },
537
- outputOptions: {
538
- ...safeUserOutputOptions,
539
- file: options.outFile,
540
- format: "esm",
541
- sourcemap: safeUserOutputOptions.sourcemap ?? options.sourcemap ?? false,
542
- minify: safeUserOutputOptions.minify ?? options.minify,
543
- codeSplitting: false,
544
- ...options.inlineDynamicImports !== undefined ? { inlineDynamicImports: options.inlineDynamicImports } : {}
545
- }
546
- };
547
- }
548
- async function writeWorkerCompatibleBundle(options) {
549
- const { rolldown } = await import("rolldown");
550
- const bundle = await rolldown(options.inputOptions);
551
- try {
552
- await bundle.write(options.outputOptions);
553
- await assertWorkerBundleHasNoDynamicImports(options.outFile);
554
- } finally {
555
- await bundle.close();
556
- }
557
- }
558
-
559
- // src/bundler/worker-bundler.ts
560
- async function resolveInternalModuleEntry(relativeCandidates) {
561
- const fs = await import("node:fs/promises");
562
- const currentFileDir = dirname(fileURLToPath(import.meta.url));
563
- for (const candidate of relativeCandidates) {
564
- const absolutePath = resolve2(currentFileDir, candidate);
565
- try {
566
- await fs.access(absolutePath);
567
- return absolutePath;
568
- } catch {}
569
- }
570
- return null;
571
- }
572
- async function resolveInternalAliasMap(outDir) {
573
- const debugShimPath = await ensureDebugShim(outDir);
574
- const runtimeEntry = await resolveInternalModuleEntry([
575
- "../runtime/index.ts",
576
- "../runtime/index.js"
577
- ]);
578
- const packageEntry = await resolveInternalModuleEntry(["../browser.ts", "../browser.js"]);
579
- return {
580
- debug: debugShimPath,
581
- ...runtimeEntry ? { "devflare/runtime": runtimeEntry } : {},
582
- ...packageEntry ? { devflare: packageEntry } : {}
583
- };
584
- }
585
- async function bundleWorkerEntry(options) {
586
- const fs = await import("node:fs/promises");
587
- const outDir = dirname(options.outFile);
588
- await fs.mkdir(outDir, { recursive: true });
589
- await fs.rm(options.outFile, { force: true });
590
- await fs.rm(`${options.outFile}.map`, { force: true });
591
- const alias = await resolveInternalAliasMap(outDir);
592
- const defaults = createWorkerdBundlerDefaults();
593
- const { inputOptions, outputOptions } = resolveWorkerCompatibleRolldownConfig({
594
- cwd: options.cwd,
595
- inputFile: options.inputFile,
596
- outFile: options.outFile,
597
- alias,
598
- ...defaults,
599
- platform: "browser",
600
- rolldownOptions: options.rolldownOptions,
601
- sourcemap: options.sourcemap ?? defaults.sourcemap,
602
- minify: options.minify ?? defaults.minify,
603
- defaultTsconfigMode: "if-present"
604
- });
605
- options.logger?.debug(`Bundling main worker → ${options.outFile}`);
606
- await writeWorkerCompatibleBundle({
607
- inputOptions,
608
- outputOptions,
609
- outFile: options.outFile
610
- });
611
- return options.outFile;
612
- }
613
-
614
- // src/bundler/do-bundler.ts
615
- import { dirname as dirname2, relative, resolve as resolve3 } from "pathe";
616
- import picomatch from "picomatch";
617
- function classToBindingName(className) {
618
- return className.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2").toUpperCase();
619
- }
620
- async function discoverDOs(cwd, pattern) {
621
- const discovered = [];
622
- const files = await discoverDurableObjectFiles(cwd, pattern);
623
- for (const [filePath, classNames] of files) {
624
- for (const className of classNames) {
625
- discovered.push({
626
- filePath,
627
- className,
628
- bindingName: classToBindingName(className)
629
- });
630
- }
631
- }
632
- return discovered;
633
- }
634
- function stripDecoratorSyntax(code) {
635
- let result = code;
636
- result = result.replace(/@durableObject\s*\([^)]*\)\s*\n?\s*(?=export\s+class)/g, "");
637
- result = result.replace(/import\s*\{([^}]*)\bdurableObject\b[^}]*\}\s*from\s*['"]devflare\/runtime['"]\s*;?/g, (match, imports) => {
638
- const cleanedImports = imports.split(",").map((s) => s.trim()).filter((s) => !s.startsWith("durableObject")).join(", ");
639
- if (cleanedImports.trim() === "") {
640
- return "";
641
- }
642
- return `import { ${cleanedImports} } from 'devflare/runtime'`;
643
- });
644
- return result;
645
- }
646
- async function bundleDOFile(sourcePath, className, outDir, cwd, bundleOptions) {
647
- const fs = await import("node:fs/promises");
648
- await fs.mkdir(outDir, { recursive: true });
649
- const sourceCode = await fs.readFile(sourcePath, "utf-8");
650
- const transformedCode = (await transformDurableObject(sourceCode, sourcePath))?.code ?? stripDecoratorSyntax(sourceCode);
651
- const entryCode = `${transformedCode}
652
-
653
- // Default export for worker (required by Miniflare)
654
- export default {
655
- async fetch(request) {
656
- return new Response('DO Worker for ${className}', { status: 200 });
657
- }
658
- };
659
- `;
660
- const virtualEntryId = resolve3(dirname2(sourcePath), `.devflare-do-${className}.virtual.ts`);
661
- const classOutDir = resolve3(outDir, className);
662
- try {
663
- await fs.rm(classOutDir, { recursive: true, force: true });
664
- } catch {}
665
- await fs.mkdir(classOutDir, { recursive: true });
666
- const debugShimPath = await ensureDebugShim(outDir);
667
- const virtualEntryPlugin = {
668
- name: "devflare-do-virtual-entry",
669
- resolveId(id) {
670
- if (id === virtualEntryId) {
671
- return virtualEntryId;
672
- }
673
- return null;
674
- },
675
- load(id) {
676
- if (id === virtualEntryId) {
677
- return entryCode;
678
- }
679
- return null;
680
- }
681
- };
682
- const userRolldownOptions = bundleOptions?.rolldownOptions;
683
- const userPlugins = userRolldownOptions?.plugins;
684
- const mergedPlugins = userPlugins === undefined ? [virtualEntryPlugin] : Array.isArray(userPlugins) ? [virtualEntryPlugin, ...userPlugins] : [virtualEntryPlugin, userPlugins];
685
- const outFile = resolve3(classOutDir, "index.js");
686
- const defaults = createWorkerdBundlerDefaults();
687
- const { inputOptions, outputOptions } = resolveWorkerCompatibleRolldownConfig({
688
- cwd,
689
- inputFile: virtualEntryId,
690
- outFile,
691
- ...defaults,
692
- platform: "neutral",
693
- alias: {
694
- debug: debugShimPath
695
- },
696
- rolldownOptions: {
697
- ...userRolldownOptions,
698
- plugins: mergedPlugins
699
- },
700
- sourcemap: bundleOptions?.sourcemap ?? defaults.sourcemap,
701
- minify: bundleOptions?.minify ?? defaults.minify,
702
- inlineDynamicImports: true,
703
- defaultTsconfigMode: "always"
704
- });
705
- await writeWorkerCompatibleBundle({
706
- inputOptions,
707
- outputOptions,
708
- outFile
709
- });
710
- return resolve3(classOutDir, "index.js");
711
- }
712
- async function bundleAllDOs(discovered, outDir, cwd, logger, bundleOptions) {
713
- const fs = await import("node:fs/promises");
714
- const bundles = new Map;
715
- const classes = new Map;
716
- const sourceFiles = new Map;
717
- const errors = [];
718
- for (const do_ of discovered) {
719
- const existing = sourceFiles.get(do_.filePath) || [];
720
- existing.push(do_.className);
721
- sourceFiles.set(do_.filePath, existing);
722
- }
723
- for (const do_ of discovered) {
724
- try {
725
- logger?.debug(`Bundling ${do_.className} from ${do_.filePath}`);
726
- const outFile = await bundleDOFile(do_.filePath, do_.className, outDir, cwd, bundleOptions);
727
- bundles.set(do_.bindingName, outFile);
728
- classes.set(do_.bindingName, do_.className);
729
- logger?.debug(` → ${outFile}`);
730
- } catch (error) {
731
- const err = error instanceof Error ? error : new Error(String(error));
732
- errors.push(err);
733
- logger?.error(`Failed to bundle ${do_.className}:`, err.message);
734
- }
735
- }
736
- return { bundles, classes, sourceFiles, errors };
737
- }
738
- function createDOBundler(options) {
739
- const { cwd, pattern, outDir, logger, onRebuild, rolldownOptions, sourcemap, minify } = options;
740
- let result = {
741
- bundles: new Map,
742
- classes: new Map,
743
- sourceFiles: new Map,
744
- errors: []
745
- };
746
- let watcher = null;
747
- let chokidarWatcher = null;
748
- async function build() {
749
- const discovered = await discoverDOs(cwd, pattern);
750
- if (discovered.length === 0) {
751
- logger?.debug("No DOs found matching pattern:", pattern);
752
- return result;
753
- }
754
- logger?.info(`Found ${discovered.length} Durable Object(s)`);
755
- for (const do_ of discovered) {
756
- logger?.info(` • ${do_.className} → ${do_.bindingName}`);
757
- }
758
- result = await bundleAllDOs(discovered, outDir, cwd, logger, {
759
- rolldownOptions,
760
- sourcemap,
761
- minify
762
- });
763
- if (result.errors.length === 0) {
764
- logger?.success(`Bundled ${result.bundles.size} DO(s) to ${outDir}`);
765
- }
766
- return result;
767
- }
768
- async function watch() {
769
- const chokidar = await import("chokidar");
770
- const files = await findFiles(pattern, { cwd });
771
- let dirsToWatch;
772
- if (files.length > 0) {
773
- dirsToWatch = [...new Set(files.map((f) => dirname2(f)))];
774
- } else {
775
- const patternDir = dirname2(pattern);
776
- const absolutePatternDir = resolve3(cwd, patternDir === "." ? "" : patternDir) || cwd;
777
- dirsToWatch = [absolutePatternDir];
778
- logger?.debug(`No DO files yet, watching pattern directory: ${absolutePatternDir}`);
779
- }
780
- logger?.info(`Watching ${files.length} DO file(s) in ${dirsToWatch.length} director(ies)...`);
781
- const isWindows = process.platform === "win32";
782
- chokidarWatcher = chokidar.watch(dirsToWatch, {
783
- ignoreInitial: true,
784
- usePolling: isWindows,
785
- interval: isWindows ? 300 : undefined,
786
- awaitWriteFinish: {
787
- stabilityThreshold: 100,
788
- pollInterval: 50
789
- },
790
- depth: 0
791
- });
792
- const normalizePath = (p) => {
793
- let normalized = p.replace(/\\/g, "/");
794
- if (isWindows && /^[a-zA-Z]:/.test(normalized)) {
795
- normalized = normalized[0].toLowerCase() + normalized.slice(1);
796
- }
797
- return normalized;
798
- };
799
- const isMatch = picomatch(pattern, {
800
- dot: true,
801
- matchBase: false
802
- });
803
- const matchesPattern = (filePath) => {
804
- const normalizedPath = normalizePath(filePath);
805
- const relativePath = relative(normalizePath(cwd), normalizedPath);
806
- return isMatch(relativePath);
807
- };
808
- let isRebuilding = false;
809
- let pendingRebuild = null;
810
- let rebuildTimeout = null;
811
- const scheduleRebuild = (changedPath) => {
812
- if (rebuildTimeout) {
813
- clearTimeout(rebuildTimeout);
814
- }
815
- rebuildTimeout = setTimeout(() => {
816
- triggerRebuild(changedPath);
817
- }, 150);
818
- };
819
- const triggerRebuild = async (changedPath) => {
820
- if (isRebuilding) {
821
- pendingRebuild = changedPath;
822
- logger?.debug(`Rebuild already in progress, queuing: ${changedPath}`);
823
- return;
824
- }
825
- isRebuilding = true;
826
- try {
827
- logger?.info(`DO file changed: ${changedPath}`);
828
- logger?.info("Rebuilding DOs...");
829
- const startTime = Date.now();
830
- result = await build();
831
- const elapsed = Date.now() - startTime;
832
- logger?.success(`DO rebuild complete (${elapsed}ms)`);
833
- await onRebuild?.(result);
834
- } catch (error) {
835
- logger?.error("DO rebuild failed:", error);
836
- } finally {
837
- isRebuilding = false;
838
- if (pendingRebuild) {
839
- const nextPath = pendingRebuild;
840
- pendingRebuild = null;
841
- triggerRebuild(nextPath);
842
- }
843
- }
844
- };
845
- chokidarWatcher.on("change", (filePath) => {
846
- if (matchesPattern(filePath)) {
847
- logger?.debug(`File changed: ${filePath}`);
848
- scheduleRebuild(filePath);
849
- }
850
- });
851
- chokidarWatcher.on("add", (filePath) => {
852
- if (matchesPattern(filePath)) {
853
- logger?.debug(`File added: ${filePath}`);
854
- scheduleRebuild(filePath);
855
- }
856
- });
857
- chokidarWatcher.on("unlink", (filePath) => {
858
- if (matchesPattern(filePath)) {
859
- logger?.debug(`File removed: ${filePath}`);
860
- scheduleRebuild(filePath);
861
- }
862
- });
863
- chokidarWatcher.on("ready", () => {
864
- logger?.info("DO file watcher ready");
865
- });
866
- chokidarWatcher.on("error", (error) => {
867
- logger?.error("DO file watcher error:", error);
868
- });
869
- }
870
- async function close() {
871
- if (watcher) {
872
- await watcher.close();
873
- watcher = null;
874
- }
875
- if (chokidarWatcher) {
876
- await chokidarWatcher.close();
877
- chokidarWatcher = null;
878
- }
879
- }
880
- function getResult() {
881
- return result;
882
- }
883
- return {
884
- build,
885
- watch,
886
- close,
887
- getResult
888
- };
889
- }
890
- export { createDOBundler, bundleWorkerEntry };