@velastack/patterns 0.3.1 → 0.3.2

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 (144) hide show
  1. package/README.md +32 -2
  2. package/dist/chunks/_layout-B7ujvjnA.js +55 -0
  3. package/dist/chunks/_layout-B7ujvjnA.js.map +1 -0
  4. package/dist/chunks/{collections-CgdvZXmh.js → collections-UPqYto13.js} +2 -2
  5. package/dist/chunks/{collections-CgdvZXmh.js.map → collections-UPqYto13.js.map} +1 -1
  6. package/dist/chunks/{compose-handle-Cg9jnCsS.js → compose-handle-B-CkDcQD.js} +23 -23
  7. package/dist/chunks/{compose-handle-Cg9jnCsS.js.map → compose-handle-B-CkDcQD.js.map} +1 -1
  8. package/dist/chunks/config-target-Bln26FJe.js +164 -0
  9. package/dist/chunks/config-target-Bln26FJe.js.map +1 -0
  10. package/dist/chunks/errors-DR3gF_7a.js +18 -0
  11. package/dist/chunks/errors-DR3gF_7a.js.map +1 -0
  12. package/dist/chunks/{generate-DRA63W0r.js → generate-6snrlnpA.js} +2 -2
  13. package/dist/chunks/{generate-DRA63W0r.js.map → generate-6snrlnpA.js.map} +1 -1
  14. package/dist/chunks/{generate-BkQ1xMDp.js → generate-C6xi5S5L.js} +4 -4
  15. package/dist/chunks/{generate-BkQ1xMDp.js.map → generate-C6xi5S5L.js.map} +1 -1
  16. package/dist/chunks/{generate-tOkjJFUf.js → generate-CyuY2Ci7.js} +4 -3
  17. package/dist/chunks/generate-CyuY2Ci7.js.map +1 -0
  18. package/dist/chunks/{generate-iQP31-m1.js → generate-DHgKgHb7.js} +4 -4
  19. package/dist/chunks/{generate-iQP31-m1.js.map → generate-DHgKgHb7.js.map} +1 -1
  20. package/dist/chunks/{generate-_LvrYK6i.js → generate-jsB_oO0b.js} +4 -4
  21. package/dist/chunks/{generate-_LvrYK6i.js.map → generate-jsB_oO0b.js.map} +1 -1
  22. package/dist/chunks/{generate.runtime-DAmYsIvF.js → generate.runtime-9R2AUKLS.js} +5 -5
  23. package/dist/chunks/{generate.runtime-DAmYsIvF.js.map → generate.runtime-9R2AUKLS.js.map} +1 -1
  24. package/dist/chunks/generate.runtime-B3yX6kl2.js +87 -0
  25. package/dist/chunks/generate.runtime-B3yX6kl2.js.map +1 -0
  26. package/dist/chunks/{generate.runtime-BKo-Nidn.js → generate.runtime-B7wkyj-8.js} +6 -6
  27. package/dist/chunks/{generate.runtime-BKo-Nidn.js.map → generate.runtime-B7wkyj-8.js.map} +1 -1
  28. package/dist/chunks/generate.runtime-BHf8p_3K.js +94 -0
  29. package/dist/chunks/generate.runtime-BHf8p_3K.js.map +1 -0
  30. package/dist/chunks/{generate.runtime-BbIN0tUZ.js → generate.runtime-BSFIwX58.js} +67 -66
  31. package/dist/chunks/generate.runtime-BSFIwX58.js.map +1 -0
  32. package/dist/chunks/{generate.runtime-BnWE4qsu.js → generate.runtime-Bb9CCwQm.js} +55 -54
  33. package/dist/chunks/generate.runtime-Bb9CCwQm.js.map +1 -0
  34. package/dist/chunks/{generate.runtime-D8vgh5MH.js → generate.runtime-BjciAjq7.js} +156 -76
  35. package/dist/chunks/generate.runtime-BjciAjq7.js.map +1 -0
  36. package/dist/chunks/{generate.runtime-BwhGDnGu.js → generate.runtime-BpTpRBdH.js} +151 -150
  37. package/dist/chunks/generate.runtime-BpTpRBdH.js.map +1 -0
  38. package/dist/chunks/{generate.runtime-D0icLb5j.js → generate.runtime-Brf08fMW.js} +11 -10
  39. package/dist/chunks/{generate.runtime-D0icLb5j.js.map → generate.runtime-Brf08fMW.js.map} +1 -1
  40. package/dist/chunks/{generate.runtime-S5RIgbQx.js → generate.runtime-C6DfW_NO.js} +98 -92
  41. package/dist/chunks/generate.runtime-C6DfW_NO.js.map +1 -0
  42. package/dist/chunks/{generate.runtime-DhkaXTq3.js → generate.runtime-C9fSqy6a.js} +61 -59
  43. package/dist/chunks/generate.runtime-C9fSqy6a.js.map +1 -0
  44. package/dist/chunks/{generate.runtime-CRYjWJRe.js → generate.runtime-CawvLUoV.js} +89 -88
  45. package/dist/chunks/generate.runtime-CawvLUoV.js.map +1 -0
  46. package/dist/chunks/{generate.runtime-DNaQxed-.js → generate.runtime-CzS7PuPN.js} +84 -83
  47. package/dist/chunks/generate.runtime-CzS7PuPN.js.map +1 -0
  48. package/dist/chunks/{generate.runtime-B0hhtyAL.js → generate.runtime-D1NZPV6C.js} +27 -26
  49. package/dist/chunks/generate.runtime-D1NZPV6C.js.map +1 -0
  50. package/dist/chunks/generate.runtime-D3baqo6a.js +111 -0
  51. package/dist/chunks/generate.runtime-D3baqo6a.js.map +1 -0
  52. package/dist/chunks/{generate.runtime-DSqkXvps.js → generate.runtime-D47djbeG.js} +15 -14
  53. package/dist/chunks/{generate.runtime-DSqkXvps.js.map → generate.runtime-D47djbeG.js.map} +1 -1
  54. package/dist/chunks/generate.runtime-D72UBiwD.js +313 -0
  55. package/dist/chunks/generate.runtime-D72UBiwD.js.map +1 -0
  56. package/dist/chunks/{generate.runtime-CcuAXuV2.js → generate.runtime-DDPoXmqN.js} +15 -14
  57. package/dist/chunks/{generate.runtime-CcuAXuV2.js.map → generate.runtime-DDPoXmqN.js.map} +1 -1
  58. package/dist/chunks/{generate.runtime-acRmiU7e.js → generate.runtime-DEnn0HKw.js} +9 -8
  59. package/dist/chunks/{generate.runtime-acRmiU7e.js.map → generate.runtime-DEnn0HKw.js.map} +1 -1
  60. package/dist/chunks/{generate.runtime-wA1G3tQ4.js → generate.runtime-DHXkw2gf.js} +38 -37
  61. package/dist/chunks/generate.runtime-DHXkw2gf.js.map +1 -0
  62. package/dist/chunks/{generate.runtime-DOuufRLr.js → generate.runtime-DIuCrH6l.js} +82 -81
  63. package/dist/chunks/generate.runtime-DIuCrH6l.js.map +1 -0
  64. package/dist/chunks/generate.runtime-DOB4U-Sa.js +57 -0
  65. package/dist/chunks/generate.runtime-DOB4U-Sa.js.map +1 -0
  66. package/dist/chunks/generate.runtime-DPAy7Cav.js +328 -0
  67. package/dist/chunks/generate.runtime-DPAy7Cav.js.map +1 -0
  68. package/dist/chunks/{generate.runtime-BORbegw_.js → generate.runtime-D_ZqiYt-.js} +123 -122
  69. package/dist/chunks/generate.runtime-D_ZqiYt-.js.map +1 -0
  70. package/dist/chunks/{generate.runtime-B49wetSx.js → generate.runtime-Dm7g_WTN.js} +43 -42
  71. package/dist/chunks/generate.runtime-Dm7g_WTN.js.map +1 -0
  72. package/dist/chunks/{generate.runtime-DoZdSh9W.js → generate.runtime-HE9rzfXz.js} +58 -57
  73. package/dist/chunks/generate.runtime-HE9rzfXz.js.map +1 -0
  74. package/dist/chunks/{generate.runtime-flFRYzpi.js → generate.runtime-ejrt1o6M.js} +62 -61
  75. package/dist/chunks/generate.runtime-ejrt1o6M.js.map +1 -0
  76. package/dist/chunks/generate.runtime-l6I-St2R.js +94 -0
  77. package/dist/chunks/generate.runtime-l6I-St2R.js.map +1 -0
  78. package/dist/chunks/modify-file-DGe7MJu_.js +46 -0
  79. package/dist/chunks/modify-file-DGe7MJu_.js.map +1 -0
  80. package/dist/chunks/{modify-svelte-config-remote-CDKs_Qi0.js → modify-svelte-config-remote-BUU_EaDf.js} +2 -2
  81. package/dist/chunks/{modify-svelte-config-remote-CDKs_Qi0.js.map → modify-svelte-config-remote-BUU_EaDf.js.map} +1 -1
  82. package/dist/chunks/{providers-DO9kMyzB.js → providers-BL9vJP_9.js} +2 -2
  83. package/dist/chunks/{providers-DO9kMyzB.js.map → providers-BL9vJP_9.js.map} +1 -1
  84. package/dist/chunks/{shared-BwHQM-a9.js → shared-DkGfltvn.js} +2 -2
  85. package/dist/chunks/{shared-BwHQM-a9.js.map → shared-DkGfltvn.js.map} +1 -1
  86. package/dist/chunks/{test-setup-B2hd8I-s.js → test-setup-DHEFKEHE.js} +23 -10
  87. package/dist/chunks/test-setup-DHEFKEHE.js.map +1 -0
  88. package/dist/chunks/ts-morph-helpers-CeduA--o.js +253 -0
  89. package/dist/chunks/ts-morph-helpers-CeduA--o.js.map +1 -0
  90. package/dist/chunks/{ui-B4Tuit-7.js → ui-B3-B3sE2.js} +3 -3
  91. package/dist/chunks/{ui-B4Tuit-7.js.map → ui-B3-B3sE2.js.map} +1 -1
  92. package/dist/chunks/{ui-jhXrsw4T.js → ui-DD4NltyN.js} +2 -2
  93. package/dist/chunks/{ui-jhXrsw4T.js.map → ui-DD4NltyN.js.map} +1 -1
  94. package/dist/chunks/unmodify-load-jfdcVZ_a.js +81 -0
  95. package/dist/chunks/unmodify-load-jfdcVZ_a.js.map +1 -0
  96. package/dist/chunks/write-result-DRwceOV3.js +452 -0
  97. package/dist/chunks/write-result-DRwceOV3.js.map +1 -0
  98. package/dist/index.d.ts +34 -0
  99. package/dist/index.js +1918 -1901
  100. package/dist/index.js.map +1 -1
  101. package/package.json +1 -1
  102. package/dist/chunks/_layout-DqH4lA_r.js +0 -47
  103. package/dist/chunks/_layout-DqH4lA_r.js.map +0 -1
  104. package/dist/chunks/config-target-Co-ij8p3.js +0 -163
  105. package/dist/chunks/config-target-Co-ij8p3.js.map +0 -1
  106. package/dist/chunks/errors-D6gyegUK.js +0 -14
  107. package/dist/chunks/errors-D6gyegUK.js.map +0 -1
  108. package/dist/chunks/generate-tOkjJFUf.js.map +0 -1
  109. package/dist/chunks/generate.runtime-B0hhtyAL.js.map +0 -1
  110. package/dist/chunks/generate.runtime-B49wetSx.js.map +0 -1
  111. package/dist/chunks/generate.runtime-B7LRx-BU.js +0 -86
  112. package/dist/chunks/generate.runtime-B7LRx-BU.js.map +0 -1
  113. package/dist/chunks/generate.runtime-BORbegw_.js.map +0 -1
  114. package/dist/chunks/generate.runtime-BbIN0tUZ.js.map +0 -1
  115. package/dist/chunks/generate.runtime-BnWE4qsu.js.map +0 -1
  116. package/dist/chunks/generate.runtime-BwhGDnGu.js.map +0 -1
  117. package/dist/chunks/generate.runtime-CCg2Pjcv.js +0 -257
  118. package/dist/chunks/generate.runtime-CCg2Pjcv.js.map +0 -1
  119. package/dist/chunks/generate.runtime-CRYjWJRe.js.map +0 -1
  120. package/dist/chunks/generate.runtime-D2e_KRj0.js +0 -56
  121. package/dist/chunks/generate.runtime-D2e_KRj0.js.map +0 -1
  122. package/dist/chunks/generate.runtime-D44gjxRA.js +0 -332
  123. package/dist/chunks/generate.runtime-D44gjxRA.js.map +0 -1
  124. package/dist/chunks/generate.runtime-D8vgh5MH.js.map +0 -1
  125. package/dist/chunks/generate.runtime-DNaQxed-.js.map +0 -1
  126. package/dist/chunks/generate.runtime-DOuufRLr.js.map +0 -1
  127. package/dist/chunks/generate.runtime-DhkaXTq3.js.map +0 -1
  128. package/dist/chunks/generate.runtime-DoZdSh9W.js.map +0 -1
  129. package/dist/chunks/generate.runtime-S5RIgbQx.js.map +0 -1
  130. package/dist/chunks/generate.runtime-WmSMWL15.js +0 -82
  131. package/dist/chunks/generate.runtime-WmSMWL15.js.map +0 -1
  132. package/dist/chunks/generate.runtime-flFRYzpi.js.map +0 -1
  133. package/dist/chunks/generate.runtime-gtpOuLNO.js +0 -110
  134. package/dist/chunks/generate.runtime-gtpOuLNO.js.map +0 -1
  135. package/dist/chunks/generate.runtime-kLxeDGnS.js +0 -93
  136. package/dist/chunks/generate.runtime-kLxeDGnS.js.map +0 -1
  137. package/dist/chunks/generate.runtime-wA1G3tQ4.js.map +0 -1
  138. package/dist/chunks/modify-file-GQD6uNgI.js +0 -254
  139. package/dist/chunks/modify-file-GQD6uNgI.js.map +0 -1
  140. package/dist/chunks/test-setup-B2hd8I-s.js.map +0 -1
  141. package/dist/chunks/unmodify-load-W1ePZQHr.js +0 -80
  142. package/dist/chunks/unmodify-load-W1ePZQHr.js.map +0 -1
  143. package/dist/chunks/write-result-DewHCNhM.js +0 -451
  144. package/dist/chunks/write-result-DewHCNhM.js.map +0 -1
package/README.md CHANGED
@@ -62,6 +62,11 @@ The `modifies` directory contains scripts that modify the target project. Modifi
62
62
  Each modification should have an extensive test suite with `fixtures/expect` and `fixtures/original` to ensure that
63
63
  the modifications work across a wide range of project setups.
64
64
 
65
+ Modifiers call `formatLikeSource(sf)` (`src/runtime/ts-morph-helpers.ts`) rather than `sf.formatText()`, whose
66
+ four-space default re-indents every line of a tab-indented file; a project without prettier has nothing to put
67
+ that back. `withInMemoryScript` takes the shared indent off a `<script>` body before ts-morph sees it and puts it
68
+ back afterwards, so an added import lines up with its neighbours.
69
+
65
70
  ### Preview-Modifies
66
71
 
67
72
  The `preview-modifies` directory is the mock modify output used only for previews. It's bundled in the same way as the `creates` directory.
@@ -90,7 +95,8 @@ The CLI detects `features.ui` and the two keys; `--ui` sets `input.ui`, which wi
90
95
 
91
96
  Default routes follow `options.routeGroups` (`{ public, app }`, each a group directory name or `null`). The CLI
92
97
  detects it, so a project without `(public)` gets `src/routes/<model>`; absent means the Vela layout. Only routes
93
- resolved by `parseRoute` (form and scaffold generators and destroyers) follow it: `enable-*` patterns still write
98
+ resolved by `parseRoute` (form and scaffold generators and destroyers) follow it, plus the demo pages of
99
+ `enable-ai` and `enable-content-negotiation`, which move themselves; the other `enable-*` patterns still write
94
100
  into `(public)` / `(app)`.
95
101
 
96
102
  Field markup that does not go through formsnap lives in `src/core/field/plain.ts`, split into a **binding**
@@ -99,6 +105,28 @@ classes, or native). `remote.ts` is the remote binding in the shadcn style, so a
99
105
  there and once in the formsnap renderer (`index.ts`). The integration suite checks the plain path against the
100
106
  `bare` baseline (`sv create`), not a Vela template.
101
107
 
108
+ ### Plain projects
109
+
110
+ Two more inputs follow the `flash` / `serverTests` convention, detected by the CLI and defaulting to what a Vela
111
+ template has:
112
+
113
+ - `metaTags` (`enable-content-negotiation`): when `false`, the demo page's `+page.ts`, which imports
114
+ `svelte-meta-tags`, is left out. Default `true`; the CLI sets it from `package.json`.
115
+ - `server` (`enable-cms`): the app runs as a Node server, so the SQLite backend can be hosted in it. Defaults to
116
+ `features.backend`; the CLI sets it when it finds `@sveltejs/adapter-node` in a project without PocketBase.
117
+ The self-hosted install also brings `@velastack/kit`, which only a backend template already has.
118
+
119
+ A pattern whose pages exist only as shadcn-svelte markup sets `requires.ui: "shadcn"`: `enable-api-keys`,
120
+ `enable-auth`, `enable-auth-remote`, `enable-blog`, `enable-notifications`, `enable-payments`,
121
+ `enable-subscriptions`, `enable-teams`, `generate-scaffold` and `generate-scaffold-remote`. Patterns with a plain
122
+ variant (the form generators, `enable-i18n`, `enable-ai`) leave it unset and follow `features.ui`. The CLI refuses
123
+ a `requires.ui: "shadcn"` pattern in a `plain` project before calling `generate`, so nothing is half-applied.
124
+ As a backstop, `installComponents()` throws `MissingShadcnError` (exported) when the project has no
125
+ `components.json`, before it writes anything.
126
+
127
+ `enable-backend` brings the server test harness to a project without one: `test/setup.ts` and, when the project
128
+ configures vitest nowhere, the `vitest.config.ts` that loads it, both reported as creates.
129
+
102
130
  ## UI components
103
131
 
104
132
  `src/ui/components/<name>` holds the components Vela ships itself (`data-table`, `multiselect`, `geopoint`,
@@ -132,7 +160,9 @@ lists in `components` is handed to `shadcn-svelte add`, which resolves it from t
132
160
  # Integration tests
133
161
 
134
162
  `npm run test:integration` scaffolds real projects with `vela create`, applies patterns the way the CLI
135
- does (feature flags re-detected from disk between steps, `getCollections` reading the live schema) and
163
+ does (feature flags re-detected from disk between steps by `integration/features.ts`, a hand-kept mirror of the
164
+ CLI's detection: `backend` is `data/` plus a PocketBase client dependency, since a self-hosted CMS also keeps
165
+ its database under `data/`; `getCollections` reading the live schema) and
136
166
  then requires zero svelte-check errors with `noUnusedLocals`, zero `failed` / `not-found` file entries and
137
167
  prettier-clean output. `integration/cases.ts` holds one case per pattern plus stacks for patterns whose
138
168
  output depends on feature detection. CI runs the five suites in parallel; see `.github/workflows/ci.yml`.
@@ -0,0 +1,55 @@
1
+ import { t as e } from "./dedent-Gq6Krl4n.js";
2
+ import { i as t, o as n, r } from "./ts-morph-helpers-CeduA--o.js";
3
+ import i from "node:fs";
4
+ import a from "node:path";
5
+ import { Project as o, QuoteKind as s } from "ts-morph";
6
+ //#region src/patterns/enable/i18n/modifies/+layout.ts
7
+ var c = e`
8
+ import { browser } from '$app/environment';
9
+ import { loadLocale } from 'wuchale/load-utils';
10
+
11
+ import { getLocale } from '$locales/main.url';
12
+ import '$locales/main.loader.svelte';
13
+ import '$locales/js.loader';
14
+ `, l = e`
15
+ export const load = async ({ url, data }) => {
16
+ const locale = getLocale(url);
17
+
18
+ if (browser) {
19
+ await loadLocale(locale);
20
+ }
21
+
22
+ return data;
23
+ };
24
+ `, u = `${c}\n\n${l}`, d = [
25
+ "Merge the wuchale loader into your existing load function in +layout.ts:",
26
+ "",
27
+ u
28
+ ].join("\n");
29
+ function f(e) {
30
+ if (!i.existsSync(e)) return i.mkdirSync(a.dirname(e), { recursive: !0 }), i.writeFileSync(e, u + "\n"), {
31
+ status: "success",
32
+ changed: !0
33
+ };
34
+ let c = i.readFileSync(e, "utf8");
35
+ if (c.includes("loadLocale") || c.includes("translateUrl")) return {
36
+ status: "success",
37
+ changed: !1
38
+ };
39
+ if (/\bexport\s+(const|function)\s+load\b/.test(c)) return {
40
+ status: "failed",
41
+ message: d
42
+ };
43
+ let f = new o({
44
+ compilerOptions: { allowJs: !0 },
45
+ manipulationSettings: { quoteKind: s.Single }
46
+ }).addSourceFileAtPath(e);
47
+ return t(f, "$app/environment", "browser"), t(f, "wuchale/load-utils", "loadLocale"), t(f, "$locales/main.url", "getLocale"), r(f, [{ moduleSpecifier: "$locales/main.loader.svelte" }, { moduleSpecifier: "$locales/js.loader" }]), f.addStatements(`\n${l}\n`), n(f), f.saveSync(), {
48
+ status: "success",
49
+ changed: !0
50
+ };
51
+ }
52
+ //#endregion
53
+ export { f as n, l as t };
54
+
55
+ //# sourceMappingURL=_layout-B7ujvjnA.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"_layout-B7ujvjnA.js","names":[],"sources":["../../src/patterns/enable/i18n/modifies/+layout.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport dedent from \"dedent\";\nimport { Project, QuoteKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport {\n ensureImports,\n ensureNamedImport,\n formatLikeSource,\n} from \"../../../../runtime/ts-morph-helpers\";\n\nconst IMPORT_SNIPPET = dedent`\n import { browser } from '$app/environment';\n import { loadLocale } from 'wuchale/load-utils';\n\n import { getLocale } from '$locales/main.url';\n import '$locales/main.loader.svelte';\n import '$locales/js.loader';\n`;\n\n/** The load `disable-i18n` looks for to take it out again. */\nexport const LOAD_STATEMENT = dedent`\n export const load = async ({ url, data }) => {\n const locale = getLocale(url);\n\n if (browser) {\n await loadLocale(locale);\n }\n\n return data;\n };\n`;\n\n/** The whole file, for a project that had no root `+layout.ts`. */\nexport const LOAD_SNIPPET = `${IMPORT_SNIPPET}\\n\\n${LOAD_STATEMENT}`;\n\nconst FAILURE_HINT = [\n \"Merge the wuchale loader into your existing load function in +layout.ts:\",\n \"\",\n LOAD_SNIPPET,\n].join(\"\\n\");\n\nexport function ensureRootLayoutI18n(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n fs.mkdirSync(path.dirname(layoutPath), { recursive: true });\n fs.writeFileSync(layoutPath, LOAD_SNIPPET + \"\\n\");\n return { status: \"success\", changed: true };\n }\n\n const existing = fs.readFileSync(layoutPath, \"utf8\");\n if (existing.includes(\"loadLocale\") || existing.includes(\"translateUrl\")) {\n return { status: \"success\", changed: false };\n }\n\n if (/\\bexport\\s+(const|function)\\s+load\\b/.test(existing)) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n // No load to merge with, but the file may hold other route options\n // (`export const prerender = true`, say), so the load is added to it\n // rather than written over it.\n const project = new Project({\n compilerOptions: { allowJs: true },\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sourceFile = project.addSourceFileAtPath(layoutPath);\n\n ensureNamedImport(sourceFile, \"$app/environment\", \"browser\");\n ensureNamedImport(sourceFile, \"wuchale/load-utils\", \"loadLocale\");\n ensureNamedImport(sourceFile, \"$locales/main.url\", \"getLocale\");\n ensureImports(sourceFile, [\n { moduleSpecifier: \"$locales/main.loader.svelte\" },\n { moduleSpecifier: \"$locales/js.loader\" },\n ]);\n\n sourceFile.addStatements(`\\n${LOAD_STATEMENT}\\n`);\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n}\n"],"mappings":";;;;;;AAWA,IAAM,IAAiB,CAAM;;;;;;;GAUhB,IAAiB,CAAM;;;;;;;;;;GAavB,IAAe,GAAG,EAAe,MAAM,KAE9C,IAAe;CACnB;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI;AAEX,SAAgB,EAAqB,GAAmC;CACtE,IAAI,CAAC,EAAG,WAAW,CAAU,GAG3B,OAFA,EAAG,UAAU,EAAK,QAAQ,CAAU,GAAG,EAAE,WAAW,GAAK,CAAC,GAC1D,EAAG,cAAc,GAAY,IAAe,IAAI,GACzC;EAAE,QAAQ;EAAW,SAAS;CAAK;CAG5C,IAAM,IAAW,EAAG,aAAa,GAAY,MAAM;CACnD,IAAI,EAAS,SAAS,YAAY,KAAK,EAAS,SAAS,cAAc,GACrE,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAI,uCAAuC,KAAK,CAAQ,GACtD,OAAO;EAAE,QAAQ;EAAU,SAAS;CAAa;CAUnD,IAAM,IAAa,IAJC,EAAQ;EAC1B,iBAAiB,EAAE,SAAS,GAAK;EACjC,sBAAsB,EAAE,WAAW,EAAU,OAAO;CACtD,CACmB,CAAA,CAAQ,oBAAoB,CAAU;CAazD,OAXA,EAAkB,GAAY,oBAAoB,SAAS,GAC3D,EAAkB,GAAY,sBAAsB,YAAY,GAChE,EAAkB,GAAY,qBAAqB,WAAW,GAC9D,EAAc,GAAY,CACxB,EAAE,iBAAiB,8BAA8B,GACjD,EAAE,iBAAiB,qBAAqB,CAC1C,CAAC,GAED,EAAW,cAAc,KAAK,EAAe,GAAG,GAChD,EAAiB,CAAU,GAC3B,EAAW,SAAS,GACb;EAAE,QAAQ;EAAW,SAAS;CAAK;AAC5C"}
@@ -1,4 +1,4 @@
1
- import { t as e } from "./errors-D6gyegUK.js";
1
+ import { t as e } from "./errors-DR3gF_7a.js";
2
2
  import { a as t } from "./util-BLYliuUK.js";
3
3
  import { n, t as r } from "./logger-CQONztPm.js";
4
4
  import { i, n as a, t as o } from "./pocketbase-CeG5BMN2.js";
@@ -189,4 +189,4 @@ async function y(e, r) {
189
189
  //#endregion
190
190
  export { m as applyCollectionFieldsPatches, f as applyCollectionRulePatches, u as createCollectionIdempotent, y as createCollections, v as dropCollections, _ as planCollectionDrops };
191
191
 
192
- //# sourceMappingURL=collections-CgdvZXmh.js.map
192
+ //# sourceMappingURL=collections-UPqYto13.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"collections-CgdvZXmh.js","names":[],"sources":["../../src/runtime/collections.ts"],"sourcesContent":["import { readFileSync } from \"node:fs\";\nimport type PocketBase from \"pocketbase\";\nimport type { CollectionModel } from \"pocketbase\";\nimport type {\n CollectionDropSpec,\n CollectionFieldSpec,\n CollectionFieldsPatch,\n CollectionRulesPatch,\n CollectionSpec,\n File,\n Options,\n} from \"../core/types\";\nimport { InvalidArgumentError } from \"../core/errors\";\nimport { getLogger, NOOP_LOGGER, type Logger } from \"../core/logger\";\nimport { languageFromPath } from \"../core/util\";\nimport { getMigrationFile, migrationDelay, withPocketbase } from \"./pocketbase\";\n\ninterface PocketBaseCollectionCreateError {\n response?: {\n data?: {\n name?: {\n code?: string;\n };\n };\n };\n message?: string;\n}\n\nfunction isCollectionAlreadyExistsError(\n error: PocketBaseCollectionCreateError,\n): boolean {\n if (\n error.response?.data?.name?.code === \"validation_collection_name_exists\"\n ) {\n return true;\n }\n\n const message = error.message?.toLowerCase() ?? \"\";\n return (\n message.includes(\"already exists\") || message.includes(\"must be unique\")\n );\n}\n\ntype CollectionCreateInput = Parameters<PocketBase[\"collections\"][\"create\"]>[0];\n\ninterface RelationFieldLike {\n type?: string;\n collectionId?: string;\n}\n\n/**\n * A spec may name the collection a relation points at (`stripe_customers`)\n * where PocketBase wants its id; specs read better by name, and the id is\n * only known once the target exists. Names are swapped for ids here, and a\n * value that already is an id (`_pb_users_auth_`) is left alone.\n */\nasync function resolveRelationTargets(\n pb: PocketBase,\n spec: CollectionCreateInput,\n): Promise<CollectionCreateInput> {\n const fields = (spec as { fields?: RelationFieldLike[] }).fields;\n const relations = (fields ?? []).filter(\n (field) => field.type === \"relation\" && field.collectionId,\n );\n if (relations.length === 0) return spec;\n\n const existing = await pb.collections.getFullList();\n const ids = new Set(existing.map((c) => c.id));\n const byName = new Map(existing.map((c) => [c.name, c.id]));\n if (relations.every((field) => ids.has(field.collectionId!))) return spec;\n\n return {\n ...spec,\n fields: fields!.map((field) => {\n if (field.type !== \"relation\" || !field.collectionId) return field;\n const id = byName.get(field.collectionId);\n return id && !ids.has(field.collectionId)\n ? { ...field, collectionId: id }\n : field;\n }),\n } as CollectionCreateInput;\n}\n\nexport interface CreateCollectionResult {\n collection: CollectionModel;\n created: boolean;\n}\n\n/**\n * Idempotent wrapper around `pb.collections.create`. If the collection already\n * exists, logs and returns the existing model with `created: false` so callers\n * can skip work tied to a fresh create (e.g. appending a newly-generated\n * migration file to the result).\n */\nexport async function createCollectionIdempotent(\n pb: PocketBase,\n spec: CollectionCreateInput,\n logger: Logger = NOOP_LOGGER,\n): Promise<CreateCollectionResult> {\n const name = (spec as { name: string }).name;\n try {\n const collection = await pb.collections.create(\n await resolveRelationTargets(pb, spec),\n );\n return { collection, created: true };\n } catch (error) {\n if (\n !isCollectionAlreadyExistsError(error as PocketBaseCollectionCreateError)\n ) {\n throw error;\n }\n logger.info(`Collection \"${name}\" already exists, skipping`);\n const collection = await pb.collections.getOne(name);\n return { collection, created: false };\n }\n}\n\nfunction rulePayloadFromPatch(\n patch: CollectionRulesPatch,\n): Record<string, unknown> {\n const payload: Record<string, unknown> = {};\n if (patch.listRule !== undefined) payload.listRule = patch.listRule;\n if (patch.viewRule !== undefined) payload.viewRule = patch.viewRule;\n if (patch.createRule !== undefined) payload.createRule = patch.createRule;\n if (patch.updateRule !== undefined) payload.updateRule = patch.updateRule;\n if (patch.deleteRule !== undefined) payload.deleteRule = patch.deleteRule;\n return payload;\n}\n\n/**\n * Applies API rule updates in array order. Call after all referenced collections exist.\n * Collects migration files produced by each update when `options` is provided.\n */\nexport async function applyCollectionRulePatches(\n pb: {\n collections: {\n getFirstListItem: (filter: string) => Promise<{ id: string }>;\n update: (id: string, body: Record<string, unknown>) => Promise<unknown>;\n };\n },\n patches: CollectionRulesPatch[],\n options?: Options,\n logger: Logger = NOOP_LOGGER,\n): Promise<File[]> {\n const migrations: File[] = [];\n\n for (const patch of patches) {\n const escaped = patch.collectionName.replace(/'/g, \"''\");\n const col = await pb.collections.getFirstListItem(`name='${escaped}'`);\n logger.info(`Updating rules on collection \"${patch.collectionName}\"`);\n await pb.collections.update(col.id, rulePayloadFromPatch(patch));\n await migrationDelay();\n\n if (options) {\n const migrationFile = getMigrationFile(\n patch.collectionName,\n \"updated\",\n options,\n );\n if (migrationFile) {\n migrations.push({\n path: migrationFile,\n language: languageFromPath(migrationFile),\n content: readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n }\n }\n }\n\n return migrations;\n}\n\nfunction applyFieldChanges(\n existing: CollectionFieldSpec[],\n patch: CollectionFieldsPatch,\n): CollectionFieldSpec[] {\n const fields = existing.map((field) => ({ ...field }));\n\n for (const change of patch.changes) {\n if (change.op === \"add\") {\n if (fields.some((f) => f.name === change.field.name)) {\n throw new InvalidArgumentError(\n `Field \"${change.field.name}\" already exists on collection \"${patch.collectionName}\"`,\n );\n }\n fields.push(change.field);\n continue;\n }\n if (change.op === \"remove\") {\n const index = fields.findIndex((f) => f.name === change.fieldName);\n if (index === -1) {\n throw new InvalidArgumentError(\n `Field \"${change.fieldName}\" does not exist on collection \"${patch.collectionName}\"`,\n );\n }\n fields.splice(index, 1);\n continue;\n }\n if (change.op === \"rename\") {\n const field = fields.find((f) => f.name === change.from);\n if (!field) {\n throw new InvalidArgumentError(\n `Field \"${change.from}\" does not exist on collection \"${patch.collectionName}\"`,\n );\n }\n if (fields.some((f) => f.name === change.to)) {\n throw new InvalidArgumentError(\n `Field \"${change.to}\" already exists on collection \"${patch.collectionName}\"`,\n );\n }\n field.name = change.to;\n continue;\n }\n }\n\n return fields;\n}\n\nexport async function applyCollectionFieldsPatches(\n pb: {\n collections: {\n getOne: (\n name: string,\n ) => Promise<{ id: string; fields: CollectionFieldSpec[] }>;\n update: (id: string, body: Record<string, unknown>) => Promise<unknown>;\n };\n },\n patches: CollectionFieldsPatch[],\n options: Options,\n logger: Logger = NOOP_LOGGER,\n): Promise<File[]> {\n const migrations: File[] = [];\n\n for (const patch of patches) {\n const collection = await pb.collections.getOne(patch.collectionName);\n const newFields = applyFieldChanges(collection.fields, patch);\n logger.info(`Updating fields on collection \"${patch.collectionName}\"`);\n await pb.collections.update(collection.id, { fields: newFields });\n await migrationDelay();\n\n const migrationFile = getMigrationFile(\n patch.collectionName,\n \"updated\",\n options,\n );\n if (!migrationFile) continue;\n\n migrations.push({\n path: migrationFile,\n language: languageFromPath(migrationFile),\n content: readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n }\n\n return migrations;\n}\n\nexport interface DropCollectionResult {\n dropped: boolean;\n existed: boolean;\n}\n\n/**\n * Idempotent collection drop. Returns `{ existed: false, dropped: false }` if\n * the collection is already gone, matching the idempotency contract of\n * `createCollectionIdempotent`.\n */\nexport async function dropCollectionIdempotent(\n pb: PocketBase,\n name: string,\n logger: Logger = NOOP_LOGGER,\n): Promise<DropCollectionResult> {\n try {\n await pb.collections.getOne(name);\n } catch (error) {\n const status = (error as { status?: number }).status;\n if (status === 404) {\n logger.info(`Collection \"${name}\" does not exist, skipping drop`);\n return { dropped: false, existed: false };\n }\n throw error;\n }\n await pb.collections.delete(name);\n return { dropped: true, existed: true };\n}\n\nexport interface CollectionStats {\n exists: boolean;\n rowCount: number;\n}\n\nexport async function getCollectionStats(\n pb: PocketBase,\n name: string,\n): Promise<CollectionStats> {\n try {\n await pb.collections.getOne(name);\n } catch (error) {\n const status = (error as { status?: number }).status;\n if (status === 404) {\n return { exists: false, rowCount: 0 };\n }\n throw error;\n }\n\n try {\n const result = await pb\n .collection(name)\n .getList(1, 1, { skipTotal: false });\n return { exists: true, rowCount: result.totalItems };\n } catch {\n return { exists: true, rowCount: 0 };\n }\n}\n\n/**\n * Resolve the set of collections to drop, with current row counts. Missing\n * collections are included with `exists: false, rowCount: 0` so callers can\n * display the full reversal plan even when some collections were already gone.\n */\nexport async function planCollectionDrops(\n pb: PocketBase,\n names: string[],\n): Promise<CollectionDropSpec[]> {\n const plans: CollectionDropSpec[] = [];\n for (const name of names) {\n const stats = await getCollectionStats(pb, name);\n plans.push({ name, exists: stats.exists, rowCount: stats.rowCount });\n }\n return plans;\n}\n\n/**\n * Drop each of the given collections (skipping those that are already gone)\n * and collect the `_deleted_<name>.js` migration file PocketBase emits for\n * each successful drop. Symmetric to `createCollections`.\n */\nexport async function dropCollections(\n specs: CollectionDropSpec[],\n options: Options,\n): Promise<File[]> {\n if (specs.length === 0) {\n return [];\n }\n\n const migrations: File[] = [];\n const logger = getLogger(options);\n\n await withPocketbase(options.root, async (pb) => {\n for (const spec of specs) {\n logger.info(`Dropping collection \"${spec.name}\"`);\n const { dropped } = await dropCollectionIdempotent(pb, spec.name, logger);\n if (!dropped) continue;\n await migrationDelay();\n\n const migrationFile = getMigrationFile(spec.name, \"deleted\", options);\n if (!migrationFile) continue;\n\n migrations.push({\n path: migrationFile,\n language: languageFromPath(migrationFile),\n content: readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n }\n });\n\n return migrations;\n}\n\nexport async function createCollections(\n collections: CollectionSpec[],\n options: Options,\n): Promise<File[]> {\n if (collections.length === 0) {\n return [];\n }\n\n const migrations: File[] = [];\n const logger = getLogger(options);\n\n await withPocketbase(options.root, async (pb) => {\n for (const collection of collections) {\n logger.info(`Creating collection \"${collection.name}\"`);\n const { created } = await createCollectionIdempotent(\n pb,\n collection,\n logger,\n );\n if (!created) continue;\n await migrationDelay();\n\n const migrationFile = getMigrationFile(\n collection.name,\n \"created\",\n options,\n );\n if (!migrationFile) {\n continue;\n }\n\n migrations.push({\n path: migrationFile,\n language: languageFromPath(migrationFile),\n content: readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n }\n });\n\n return migrations;\n}\n"],"mappings":";;;;;;AA4BA,SAAS,EACP,GACS;CACT,IACE,EAAM,UAAU,MAAM,MAAM,SAAS,qCAErC,OAAO;CAGT,IAAM,IAAU,EAAM,SAAS,YAAY,KAAK;CAChD,OACE,EAAQ,SAAS,gBAAgB,KAAK,EAAQ,SAAS,gBAAgB;AAE3E;AAeA,eAAe,EACb,GACA,GACgC;CAChC,IAAM,IAAU,EAA0C,QACpD,KAAa,KAAU,CAAC,EAAA,CAAG,QAC9B,MAAU,EAAM,SAAS,cAAc,EAAM,YAChD;CACA,IAAI,EAAU,WAAW,GAAG,OAAO;CAEnC,IAAM,IAAW,MAAM,EAAG,YAAY,YAAY,GAC5C,IAAM,IAAI,IAAI,EAAS,KAAK,MAAM,EAAE,EAAE,CAAC,GACvC,IAAS,IAAI,IAAI,EAAS,KAAK,MAAM,CAAC,EAAE,MAAM,EAAE,EAAE,CAAC,CAAC;CAG1D,OAFI,EAAU,OAAO,MAAU,EAAI,IAAI,EAAM,YAAa,CAAC,IAAU,IAE9D;EACL,GAAG;EACH,QAAQ,EAAQ,KAAK,MAAU;GAC7B,IAAI,EAAM,SAAS,cAAc,CAAC,EAAM,cAAc,OAAO;GAC7D,IAAM,IAAK,EAAO,IAAI,EAAM,YAAY;GACxC,OAAO,KAAM,CAAC,EAAI,IAAI,EAAM,YAAY,IACpC;IAAE,GAAG;IAAO,cAAc;GAAG,IAC7B;EACN,CAAC;CACH;AACF;AAaA,eAAsB,EACpB,GACA,GACA,IAAiB,GACgB;CACjC,IAAM,IAAQ,EAA0B;CACxC,IAAI;EAIF,OAAO;GAAE,YAAA,MAHgB,EAAG,YAAY,OACtC,MAAM,EAAuB,G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AChD,IAAM,EAAE,eAAY,MAAM,EAAyB,GAAI,EAAK,MAAM,CAAM;GACxE,IAAI,CAAC,GAAS;GACd,MAAM,EAAe;GAErB,IAAM,IAAgB,EAAiB,EAAK,MAAM,WAAW,CAAO;GAC/D,KAEL,EAAW,KAAK;IACd,MAAM;IACN,UAAU,EAAiB,CAAa;IACxC,SAAS,EAAa,GAAe,MAAM;IAC3C,QAAQ;GACV,CAAC;EACH;CACF,CAAC,GAEM;AACT;AAEA,eAAsB,EACpB,GACA,GACiB;CACjB,IAAI,EAAY,WAAW,GACzB,OAAO,CAAC;CAGV,IAAM,IAAqB,CAAC,GACtB,IAAS,EAAU,CAAO;CA+BhC,OA7BA,MAAM,EAAe,EAAQ,MAAM,OAAO,MAAO;EAC/C,KAAK,IAAM,KAAc,GAAa;GACpC,EAAO,KAAK,wBAAwB,EAAW,KAAK,EAAE;GACtD,IAAM,EAAE,eAAY,MAAM,EACxB,GACA,GACA,CACF;GACA,IAAI,CAAC,GAAS;GACd,MAAM,EAAe;GAErB,IAAM,IAAgB,EACpB,EAAW,MACX,WACA,CACF;GACK,KAIL,EAAW,KAAK;IACd,MAAM;IACN,UAAU,EAAiB,CAAa;IACxC,SAAS,EAAa,GAAe,MAAM;IAC3C,QAAQ;GACV,CAAC;EACH;CACF,CAAC,GAEM;AACT"}
1
+ {"version":3,"file":"collections-UPqYto13.js","names":[],"sources":["../../src/runtime/collections.ts"],"sourcesContent":["import { readFileSync } from \"node:fs\";\nimport type PocketBase from \"pocketbase\";\nimport type { CollectionModel } from \"pocketbase\";\nimport type {\n CollectionDropSpec,\n CollectionFieldSpec,\n CollectionFieldsPatch,\n CollectionRulesPatch,\n CollectionSpec,\n File,\n Options,\n} from \"../core/types\";\nimport { InvalidArgumentError } from \"../core/errors\";\nimport { getLogger, NOOP_LOGGER, type Logger } from \"../core/logger\";\nimport { languageFromPath } from \"../core/util\";\nimport { getMigrationFile, migrationDelay, withPocketbase } from \"./pocketbase\";\n\ninterface PocketBaseCollectionCreateError {\n response?: {\n data?: {\n name?: {\n code?: string;\n };\n };\n };\n message?: string;\n}\n\nfunction isCollectionAlreadyExistsError(\n error: PocketBaseCollectionCreateError,\n): boolean {\n if (\n error.response?.data?.name?.code === \"validation_collection_name_exists\"\n ) {\n return true;\n }\n\n const message = error.message?.toLowerCase() ?? \"\";\n return (\n message.includes(\"already exists\") || message.includes(\"must be unique\")\n );\n}\n\ntype CollectionCreateInput = Parameters<PocketBase[\"collections\"][\"create\"]>[0];\n\ninterface RelationFieldLike {\n type?: string;\n collectionId?: string;\n}\n\n/**\n * A spec may name the collection a relation points at (`stripe_customers`)\n * where PocketBase wants its id; specs read better by name, and the id is\n * only known once the target exists. Names are swapped for ids here, and a\n * value that already is an id (`_pb_users_auth_`) is left alone.\n */\nasync function resolveRelationTargets(\n pb: PocketBase,\n spec: CollectionCreateInput,\n): Promise<CollectionCreateInput> {\n const fields = (spec as { fields?: RelationFieldLike[] }).fields;\n const relations = (fields ?? []).filter(\n (field) => field.type === \"relation\" && field.collectionId,\n );\n if (relations.length === 0) return spec;\n\n const existing = await pb.collections.getFullList();\n const ids = new Set(existing.map((c) => c.id));\n const byName = new Map(existing.map((c) => [c.name, c.id]));\n if (relations.every((field) => ids.has(field.collectionId!))) return spec;\n\n return {\n ...spec,\n fields: fields!.map((field) => {\n if (field.type !== \"relation\" || !field.collectionId) return field;\n const id = byName.get(field.collectionId);\n return id && !ids.has(field.collectionId)\n ? { ...field, collectionId: id }\n : field;\n }),\n } as CollectionCreateInput;\n}\n\nexport interface CreateCollectionResult {\n collection: CollectionModel;\n created: boolean;\n}\n\n/**\n * Idempotent wrapper around `pb.collections.create`. If the collection already\n * exists, logs and returns the existing model with `created: false` so callers\n * can skip work tied to a fresh create (e.g. appending a newly-generated\n * migration file to the result).\n */\nexport async function createCollectionIdempotent(\n pb: PocketBase,\n spec: CollectionCreateInput,\n logger: Logger = NOOP_LOGGER,\n): Promise<CreateCollectionResult> {\n const name = (spec as { name: string }).name;\n try {\n const collection = await pb.collections.create(\n await resolveRelationTargets(pb, spec),\n );\n return { collection, created: true };\n } catch (error) {\n if (\n !isCollectionAlreadyExistsError(error as PocketBaseCollectionCreateError)\n ) {\n throw error;\n }\n logger.info(`Collection \"${name}\" already exists, skipping`);\n const collection = await pb.collections.getOne(name);\n return { collection, created: false };\n }\n}\n\nfunction rulePayloadFromPatch(\n patch: CollectionRulesPatch,\n): Record<string, unknown> {\n const payload: Record<string, unknown> = {};\n if (patch.listRule !== undefined) payload.listRule = patch.listRule;\n if (patch.viewRule !== undefined) payload.viewRule = patch.viewRule;\n if (patch.createRule !== undefined) payload.createRule = patch.createRule;\n if (patch.updateRule !== undefined) payload.updateRule = patch.updateRule;\n if (patch.deleteRule !== undefined) payload.deleteRule = patch.deleteRule;\n return payload;\n}\n\n/**\n * Applies API rule updates in array order. Call after all referenced collections exist.\n * Collects migration files produced by each update when `options` is provided.\n */\nexport async function applyCollectionRulePatches(\n pb: {\n collections: {\n getFirstListItem: (filter: string) => Promise<{ id: string }>;\n update: (id: string, body: Record<string, unknown>) => Promise<unknown>;\n };\n },\n patches: CollectionRulesPatch[],\n options?: Options,\n logger: Logger = NOOP_LOGGER,\n): Promise<File[]> {\n const migrations: File[] = [];\n\n for (const patch of patches) {\n const escaped = patch.collectionName.replace(/'/g, \"''\");\n const col = await pb.collections.getFirstListItem(`name='${escaped}'`);\n logger.info(`Updating rules on collection \"${patch.collectionName}\"`);\n await pb.collections.update(col.id, rulePayloadFromPatch(patch));\n await migrationDelay();\n\n if (options) {\n const migrationFile = getMigrationFile(\n patch.collectionName,\n \"updated\",\n options,\n );\n if (migrationFile) {\n migrations.push({\n path: migrationFile,\n language: languageFromPath(migrationFile),\n content: readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n }\n }\n }\n\n return migrations;\n}\n\nfunction applyFieldChanges(\n existing: CollectionFieldSpec[],\n patch: CollectionFieldsPatch,\n): CollectionFieldSpec[] {\n const fields = existing.map((field) => ({ ...field }));\n\n for (const change of patch.changes) {\n if (change.op === \"add\") {\n if (fields.some((f) => f.name === change.field.name)) {\n throw new InvalidArgumentError(\n `Field \"${change.field.name}\" already exists on collection \"${patch.collectionName}\"`,\n );\n }\n fields.push(change.field);\n continue;\n }\n if (change.op === \"remove\") {\n const index = fields.findIndex((f) => f.name === change.fieldName);\n if (index === -1) {\n throw new InvalidArgumentError(\n `Field \"${change.fieldName}\" does not exist on collection \"${patch.collectionName}\"`,\n );\n }\n fields.splice(index, 1);\n continue;\n }\n if (change.op === \"rename\") {\n const field = fields.find((f) => f.name === change.from);\n if (!field) {\n throw new InvalidArgumentError(\n `Field \"${change.from}\" does not exist on collection \"${patch.collectionName}\"`,\n );\n }\n if (fields.some((f) => f.name === change.to)) {\n throw new InvalidArgumentError(\n `Field \"${change.to}\" already exists on collection \"${patch.collectionName}\"`,\n );\n }\n field.name = change.to;\n continue;\n }\n }\n\n return fields;\n}\n\nexport async function applyCollectionFieldsPatches(\n pb: {\n collections: {\n getOne: (\n name: string,\n ) => Promise<{ id: string; fields: CollectionFieldSpec[] }>;\n update: (id: string, body: Record<string, unknown>) => Promise<unknown>;\n };\n },\n patches: CollectionFieldsPatch[],\n options: Options,\n logger: Logger = NOOP_LOGGER,\n): Promise<File[]> {\n const migrations: File[] = [];\n\n for (const patch of patches) {\n const collection = await pb.collections.getOne(patch.collectionName);\n const newFields = applyFieldChanges(collection.fields, patch);\n logger.info(`Updating fields on collection \"${patch.collectionName}\"`);\n await pb.collections.update(collection.id, { fields: newFields });\n await migrationDelay();\n\n const migrationFile = getMigrationFile(\n patch.collectionName,\n \"updated\",\n options,\n );\n if (!migrationFile) continue;\n\n migrations.push({\n path: migrationFile,\n language: languageFromPath(migrationFile),\n content: readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n }\n\n return migrations;\n}\n\nexport interface DropCollectionResult {\n dropped: boolean;\n existed: boolean;\n}\n\n/**\n * Idempotent collection drop. Returns `{ existed: false, dropped: false }` if\n * the collection is already gone, matching the idempotency contract of\n * `createCollectionIdempotent`.\n */\nexport async function dropCollectionIdempotent(\n pb: PocketBase,\n name: string,\n logger: Logger = NOOP_LOGGER,\n): Promise<DropCollectionResult> {\n try {\n await pb.collections.getOne(name);\n } catch (error) {\n const status = (error as { status?: number }).status;\n if (status === 404) {\n logger.info(`Collection \"${name}\" does not exist, skipping drop`);\n return { dropped: false, existed: false };\n }\n throw error;\n }\n await pb.collections.delete(name);\n return { dropped: true, existed: true };\n}\n\nexport interface CollectionStats {\n exists: boolean;\n rowCount: number;\n}\n\nexport async function getCollectionStats(\n pb: PocketBase,\n name: string,\n): Promise<CollectionStats> {\n try {\n await pb.collections.getOne(name);\n } catch (error) {\n const status = (error as { status?: number }).status;\n if (status === 404) {\n return { exists: false, rowCount: 0 };\n }\n throw error;\n }\n\n try {\n const result = await pb\n .collection(name)\n .getList(1, 1, { skipTotal: false });\n return { exists: true, rowCount: result.totalItems };\n } catch {\n return { exists: true, rowCount: 0 };\n }\n}\n\n/**\n * Resolve the set of collections to drop, with current row counts. Missing\n * collections are included with `exists: false, rowCount: 0` so callers can\n * display the full reversal plan even when some collections were already gone.\n */\nexport async function planCollectionDrops(\n pb: PocketBase,\n names: string[],\n): Promise<CollectionDropSpec[]> {\n const plans: CollectionDropSpec[] = [];\n for (const name of names) {\n const stats = await getCollectionStats(pb, name);\n plans.push({ name, exists: stats.exists, rowCount: stats.rowCount });\n }\n return plans;\n}\n\n/**\n * Drop each of the given collections (skipping those that are already gone)\n * and collect the `_deleted_<name>.js` migration file PocketBase emits for\n * each successful drop. Symmetric to `createCollections`.\n */\nexport async function dropCollections(\n specs: CollectionDropSpec[],\n options: Options,\n): Promise<File[]> {\n if (specs.length === 0) {\n return [];\n }\n\n const migrations: File[] = [];\n const logger = getLogger(options);\n\n await withPocketbase(options.root, async (pb) => {\n for (const spec of specs) {\n logger.info(`Dropping collection \"${spec.name}\"`);\n const { dropped } = await dropCollectionIdempotent(pb, spec.name, logger);\n if (!dropped) continue;\n await migrationDelay();\n\n const migrationFile = getMigrationFile(spec.name, \"deleted\", options);\n if (!migrationFile) continue;\n\n migrations.push({\n path: migrationFile,\n language: languageFromPath(migrationFile),\n content: readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n }\n });\n\n return migrations;\n}\n\nexport async function createCollections(\n collections: CollectionSpec[],\n options: Options,\n): Promise<File[]> {\n if (collections.length === 0) {\n return [];\n }\n\n const migrations: File[] = [];\n const logger = getLogger(options);\n\n await withPocketbase(options.root, async (pb) => {\n for (const collection of collections) {\n logger.info(`Creating collection \"${collection.name}\"`);\n const { created } = await createCollectionIdempotent(\n pb,\n collection,\n logger,\n );\n if (!created) continue;\n await migrationDelay();\n\n const migrationFile = getMigrationFile(\n collection.name,\n \"created\",\n options,\n );\n if (!migrationFile) {\n continue;\n }\n\n migrations.push({\n path: migrationFile,\n language: languageFromPath(migrationFile),\n content: readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n }\n });\n\n return migrations;\n}\n"],"mappings":";;;;;;AA4BA,SAAS,EACP,GACS;CACT,IACE,EAAM,UAAU,MAAM,MAAM,SAAS,qCAErC,OAAO;CAGT,IAAM,IAAU,EAAM,SAAS,YAAY,KAAK;CAChD,OACE,EAAQ,SAAS,gBAAgB,KAAK,EAAQ,SAAS,gBAAgB;AAE3E;AAeA,eAAe,EACb,GACA,GACgC;CAChC,IAAM,IAAU,EAA0C,QACpD,KAAa,KAAU,CAAC,EAAA,CAAG,QAC9B,MAAU,EAAM,SAAS,cAAc,EAAM,YAChD;CACA,IAAI,EAAU,WAAW,GAAG,OAAO;CAEnC,IAAM,IAAW,MAAM,EAAG,YAAY,YAAY,GAC5C,IAAM,IAAI,IAAI,EAAS,KAAK,MAAM,EAAE,EAAE,CAAC,GACvC,IAAS,IAAI,IAAI,EAAS,KAAK,MAAM,CAAC,EAAE,MAAM,EAAE,EAAE,CAAC,CAAC;CAG1D,OAFI,EAAU,OAAO,MAAU,EAAI,IAAI,EAAM,YAAa,CAAC,IA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 -1,4 +1,4 @@
1
- import { f as e, l as t, n, s as r } from "./modify-file-GQD6uNgI.js";
1
+ import { d as e, l as t, m as n, n as r } from "./ts-morph-helpers-CeduA--o.js";
2
2
  import { Node as i, SyntaxKind as a, ts as o } from "ts-morph";
3
3
  //#region src/runtime/compose-handle.ts
4
4
  var s = "@sveltejs/kit/hooks", c = "handleApp";
@@ -80,9 +80,9 @@ function p(e, t) {
80
80
  moduleSpecifier: s
81
81
  });
82
82
  }
83
- function m(e) {
84
- let { wasRemoved: r } = t(e, s, "sequence");
85
- r && n(e);
83
+ function m(t) {
84
+ let { wasRemoved: n } = e(t, s, "sequence");
85
+ n && r(t);
86
86
  }
87
87
  function h(e, t) {
88
88
  if (!i.isCallExpression(e)) return !1;
@@ -190,12 +190,12 @@ function j(e) {
190
190
  reason: e
191
191
  };
192
192
  }
193
- function M(t, n) {
194
- let r = !n.inlineExport;
195
- if (n.kind === "variable" && n.statement.getDeclarations().length > 1 ? n.decl.remove() : e(t, D(n)), r) for (let e of t.getExportDeclarations()) {
196
- if (e.getModuleSpecifier() !== void 0) continue;
197
- let t = e.getNamedExports().find((e) => e.getName() === "handle");
198
- t && (e.getNamedExports().length === 1 ? e.remove() : t.remove());
193
+ function M(e, t) {
194
+ let r = !t.inlineExport;
195
+ if (t.kind === "variable" && t.statement.getDeclarations().length > 1 ? t.decl.remove() : n(e, D(t)), r) for (let t of e.getExportDeclarations()) {
196
+ if (t.getModuleSpecifier() !== void 0) continue;
197
+ let e = t.getNamedExports().find((e) => e.getName() === "handle");
198
+ e && (t.getNamedExports().length === 1 ? t.remove() : e.remove());
199
199
  }
200
200
  }
201
201
  function N(e, t, n, r, i) {
@@ -298,25 +298,25 @@ function L(e, t) {
298
298
  }
299
299
  return m(e), k(e);
300
300
  }
301
- function R(e, t, n) {
302
- let i = n.name ?? n.expression, a = l(e);
301
+ function R(e, n, r) {
302
+ let i = r.name ?? r.expression, a = l(e);
303
303
  if ("unsupported" in a) return j(a.unsupported);
304
304
  let { site: o } = a;
305
- if (!o || o.kind === "function") return F(e, n);
305
+ if (!o || o.kind === "function") return F(e, r);
306
306
  let s = u(e), c = g(o.decl.getInitializerOrThrow());
307
- if (_(c, i) || v(c, i, s)) return _(c, t) || v(c, t, s) ? L(e, t) : A(o);
308
- if (_(c, t)) return c.replaceWithText(n.expression), r(e, e.getVariableStatementOrThrow("handle")), k(e);
309
- let d = v(c, t, s);
307
+ if (_(c, i) || v(c, i, s)) return _(c, n) || v(c, n, s) ? L(e, n) : A(o);
308
+ if (_(c, n)) return c.replaceWithText(r.expression), t(e, e.getVariableStatementOrThrow("handle")), k(e);
309
+ let d = v(c, n, s);
310
310
  if (d) {
311
- let t = d.calls[d.calls.length - 1], r = x(t);
312
- return r[d.index] = {
313
- ...r[d.index],
314
- text: n.expression
315
- }, E(t, r), k(e);
311
+ let t = d.calls[d.calls.length - 1], n = x(t);
312
+ return n[d.index] = {
313
+ ...n[d.index],
314
+ text: r.expression
315
+ }, E(t, n), k(e);
316
316
  }
317
- return y(c, t) ? j("ambiguous-reference") : F(e, n);
317
+ return y(c, n) ? j("ambiguous-reference") : F(e, r);
318
318
  }
319
319
  //#endregion
320
320
  export { L as n, R as r, F as t };
321
321
 
322
- //# sourceMappingURL=compose-handle-Cg9jnCsS.js.map
322
+ //# sourceMappingURL=compose-handle-B-CkDcQD.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"compose-handle-Cg9jnCsS.js","names":[],"sources":["../../src/runtime/compose-handle.ts"],"sourcesContent":["import {\n Node,\n SyntaxKind,\n ts,\n type CallExpression,\n type Expression,\n type FunctionDeclaration,\n type SourceFile,\n type Statement,\n type VariableDeclaration,\n type VariableStatement,\n} from \"ts-morph\";\nimport {\n ensureBlankLineAfterImports,\n removeAttachedComments,\n removeNamedImportIfUnused,\n removeStatementWithComments,\n} from \"./ts-morph-helpers\";\n\n/**\n * Composes the server `handle` hook in `hooks.server.ts`.\n *\n * Patterns add and subtract handles in the exported `handle` without caring\n * what shape it is in: a lone expression becomes `sequence(new, old)`, a\n * `sequence(...)` gains or loses an argument, and a handle that is a function\n * is moved to a local `handleApp` so it can take part. Subtracting back to one\n * handle unwraps the `sequence` again, and puts a `handleApp` back the way it\n * was written, so enabling then disabling a pattern round-trips.\n *\n * Nothing here formats or saves: callers do, as they always have. A result of\n * `unsupported` means the file was left exactly as it was found.\n */\n\nconst KIT_HOOKS = \"@sveltejs/kit/hooks\";\nconst EXTRACTED = \"handleApp\";\n\nexport interface HandleSpec {\n /** Source text of the sequence argument: `handleWuchale`, `handlePocketbase({ ... })`. */\n expression: string;\n /** Identifier, or callee identifier, that marks this handle. Defaults to `expression`. */\n name?: string;\n /** Where it goes in the chain. */\n position?: \"first\" | \"last\";\n}\n\nexport type Unsupported =\n /** `export { handle } from '…'`, `export { x as handle }`, or `export *` with no local handle. */\n | \"re-export\"\n /** A local `handle` SvelteKit cannot see. */\n | \"not-exported\"\n /** `export const { handle } = …` */\n | \"destructured\"\n /** `export default function handle` */\n | \"default-export\"\n /** `export let handle;` */\n | \"no-initializer\"\n /** A `sequence` in scope that is not `@sveltejs/kit/hooks`'. */\n | \"foreign-sequence\"\n /** The handle has to move to `handleApp`, and the name is taken. */\n | \"name-collision\"\n /** The handle has to move to `handleApp`, and shares its statement with other declarations. */\n | \"multi-declarator\"\n /** The handle is referenced outside the composition (`dev ? a : handleX`, or inside a function handle). */\n | \"ambiguous-reference\";\n\nexport type ComposeResult =\n /** `statement` is the `handle` declaration, when there still is one. */\n | { status: \"changed\"; statement?: Statement }\n | { status: \"unchanged\"; statement?: Statement }\n | { status: \"unsupported\"; reason: Unsupported };\n\ntype Site =\n | {\n kind: \"variable\";\n decl: VariableDeclaration;\n statement: VariableStatement;\n inlineExport: boolean;\n }\n | { kind: \"function\"; fn: FunctionDeclaration; inlineExport: boolean };\n\ntype Located =\n { site: Site | null; starExport: boolean } | { unsupported: Unsupported };\n\n/** A `sequence(...)` argument with the comments that belong to it. */\ninterface Piece {\n leading: string[];\n text: string;\n trailing: string[];\n}\n\n/** How `sequence` from `@sveltejs/kit/hooks` is bound in this file, if at all. */\ninterface KitSequence {\n local: string | null;\n namespace: string | null;\n}\n\n/** Find the exported `handle`, or say why it cannot be composed. */\nfunction locate(sf: SourceFile): Located {\n let exportedBySpecifier = false;\n let starExport = false;\n\n for (const ed of sf.getExportDeclarations()) {\n const fromModule = ed.getModuleSpecifier() !== undefined;\n if (ed.isNamespaceExport()) {\n if (ed.getNamespaceExport()?.getName() === \"handle\") {\n return { unsupported: \"re-export\" };\n }\n if (fromModule) starExport = true;\n continue;\n }\n for (const spec of ed.getNamedExports()) {\n const exported = spec.getAliasNode()?.getText() ?? spec.getName();\n if (exported !== \"handle\") continue;\n if (fromModule || spec.getName() !== \"handle\") {\n return { unsupported: \"re-export\" };\n }\n exportedBySpecifier = true;\n }\n }\n\n const fn = sf.getFunctions().find((f) => f.getName() === \"handle\");\n if (fn) {\n if (fn.isDefaultExport()) return { unsupported: \"default-export\" };\n if (!fn.hasExportKeyword() && !exportedBySpecifier) {\n return { unsupported: \"not-exported\" };\n }\n return {\n site: { kind: \"function\", fn, inlineExport: fn.hasExportKeyword() },\n starExport,\n };\n }\n\n for (const statement of sf.getVariableStatements()) {\n for (const decl of statement.getDeclarations()) {\n const nameNode = decl.getNameNode();\n if (!Node.isIdentifier(nameNode)) {\n const bindsHandle = nameNode\n .getDescendantsOfKind(SyntaxKind.BindingElement)\n .some((el) => el.getNameNode().getText() === \"handle\");\n if (bindsHandle) return { unsupported: \"destructured\" };\n continue;\n }\n if (nameNode.getText() !== \"handle\") continue;\n if (!statement.hasExportKeyword() && !exportedBySpecifier) {\n return { unsupported: \"not-exported\" };\n }\n if (!decl.getInitializer()) return { unsupported: \"no-initializer\" };\n return {\n site: {\n kind: \"variable\",\n decl,\n statement,\n inlineExport: statement.hasExportKeyword(),\n },\n starExport,\n };\n }\n }\n\n // `export { handle }` naming something that is not a local variable or\n // function: an import passed straight through, or a class.\n if (exportedBySpecifier) return { unsupported: \"re-export\" };\n return { site: null, starExport };\n}\n\nfunction kitSequence(sf: SourceFile): KitSequence {\n const found: KitSequence = { local: null, namespace: null };\n for (const decl of sf.getImportDeclarations()) {\n if (decl.getModuleSpecifierValue() !== KIT_HOOKS || decl.isTypeOnly()) {\n continue;\n }\n const namespace = decl.getNamespaceImport();\n if (namespace) found.namespace = namespace.getText();\n for (const named of decl.getNamedImports()) {\n if (named.getName() !== \"sequence\" || named.isTypeOnly()) continue;\n found.local = named.getAliasNode()?.getText() ?? \"sequence\";\n }\n }\n return found;\n}\n\n/** Whether `name` is declared at the top level or imported. */\nfunction isBound(sf: SourceFile, name: string): boolean {\n for (const decl of sf.getImportDeclarations()) {\n if (decl.getDefaultImport()?.getText() === name) return true;\n if (decl.getNamespaceImport()?.getText() === name) return true;\n for (const named of decl.getNamedImports()) {\n if ((named.getAliasNode()?.getText() ?? named.getName()) === name) {\n return true;\n }\n }\n }\n if (sf.getFunction(name) || sf.getClass(name) || sf.getEnum(name)) {\n return true;\n }\n return sf.getVariableDeclarations().some((d) => {\n const nameNode = d.getNameNode();\n if (Node.isIdentifier(nameNode)) return nameNode.getText() === name;\n return nameNode\n .getDescendantsOfKind(SyntaxKind.BindingElement)\n .some((el) => el.getNameNode().getText() === name);\n });\n}\n\n/** The callee to write for a new `sequence(...)`, or null when none can be had. */\nfunction sequenceCallee(sf: SourceFile, kit: KitSequence): string | null {\n if (kit.local) return kit.local;\n if (kit.namespace) return `${kit.namespace}.sequence`;\n return isBound(sf, \"sequence\") ? null : \"sequence\";\n}\n\nfunction ensureSequenceImport(sf: SourceFile, kit: KitSequence): void {\n if (kit.local || kit.namespace) return;\n const decl = sf\n .getImportDeclarations()\n .find(\n (d) =>\n d.getModuleSpecifierValue() === KIT_HOOKS &&\n !d.isTypeOnly() &&\n !d.getNamespaceImport(),\n );\n if (decl) decl.addNamedImport(\"sequence\");\n else {\n sf.addImportDeclaration({\n namedImports: [\"sequence\"],\n moduleSpecifier: KIT_HOOKS,\n });\n }\n}\n\nfunction pruneSequenceImport(sf: SourceFile): void {\n // ts-morph takes the blank line after the imports with a removed import.\n const { wasRemoved } = removeNamedImportIfUnused(sf, KIT_HOOKS, \"sequence\");\n if (wasRemoved) ensureBlankLineAfterImports(sf);\n}\n\nfunction isSequenceCall(node: Node, kit: KitSequence): node is CallExpression {\n if (!Node.isCallExpression(node)) return false;\n const callee = node.getExpression();\n if (Node.isIdentifier(callee)) return callee.getText() === kit.local;\n if (Node.isPropertyAccessExpression(callee)) {\n return (\n kit.namespace !== null &&\n callee.getExpression().getText() === kit.namespace &&\n callee.getName() === \"sequence\"\n );\n }\n return false;\n}\n\n/** Strip `( )`, `satisfies T`, `as T`, `<T>` and `!` down to the composition. */\nfunction unwrap(node: Expression): Expression {\n for (;;) {\n if (\n Node.isParenthesizedExpression(node) ||\n Node.isSatisfiesExpression(node) ||\n Node.isAsExpression(node) ||\n Node.isTypeAssertion(node) ||\n Node.isNonNullExpression(node)\n ) {\n node = node.getExpression();\n } else {\n return node;\n }\n }\n}\n\n/** `name`, or a call of `name`: `handleWuchale`, `handlePocketbase({ ... })`. */\nfunction isHandle(node: Node, name: string): boolean {\n if (Node.isIdentifier(node)) return node.getText() === name;\n if (Node.isCallExpression(node)) {\n const callee = node.getExpression();\n return Node.isIdentifier(callee) && callee.getText() === name;\n }\n return false;\n}\n\n/** The chain of `sequence` calls down to the argument that is `name`. */\nfunction findInSequence(\n node: Node,\n name: string,\n kit: KitSequence,\n): { calls: CallExpression[]; index: number } | null {\n if (!isSequenceCall(node, kit)) return null;\n const args = node.getArguments();\n const index = args.findIndex((arg) => isHandle(arg, name));\n if (index >= 0) return { calls: [node], index };\n for (const arg of args) {\n const inner = findInSequence(arg, name, kit);\n if (inner) return { calls: [node, ...inner.calls], index: inner.index };\n }\n return null;\n}\n\nfunction references(node: Node, name: string): boolean {\n if (Node.isIdentifier(node) && node.getText() === name) return true;\n return node\n .getDescendantsOfKind(SyntaxKind.Identifier)\n .some((id) => id.getText() === name);\n}\n\nfunction commentTexts(text: string, ranges: ts.CommentRange[]): string[] {\n return ranges.map((r) => text.slice(r.pos, r.end));\n}\n\n/**\n * The arguments of a `sequence(...)` call, each with its comments. A comment\n * after an argument's comma on the same line is that argument's; comments on\n * the lines above an argument are its own too.\n */\nfunction pieces(call: CallExpression): Piece[] {\n const text = call.getSourceFile().getFullText();\n const args = call.getArguments();\n const openParen = call.getFirstChildByKindOrThrow(SyntaxKind.OpenParenToken);\n const closeParen = call.getLastChildByKindOrThrow(SyntaxKind.CloseParenToken);\n\n const result = args.map((arg, i): Piece => {\n let leadingFrom = openParen.getEnd();\n if (i > 0) {\n const prevComma = args[i - 1].getNextSiblingIfKind(SyntaxKind.CommaToken);\n leadingFrom = prevComma?.getEnd() ?? args[i - 1].getEnd();\n const prevTrailing = ts.getTrailingCommentRanges(text, leadingFrom);\n if (prevTrailing?.length) {\n leadingFrom = prevTrailing[prevTrailing.length - 1].end;\n }\n }\n const leading = (\n ts.getLeadingCommentRanges(text, leadingFrom) ?? []\n ).filter((r) => r.end <= arg.getStart());\n const comma = arg.getNextSiblingIfKind(SyntaxKind.CommaToken);\n const trailing =\n ts.getTrailingCommentRanges(text, comma?.getEnd() ?? arg.getEnd()) ?? [];\n return {\n leading: commentTexts(text, leading),\n text: arg.getText(),\n trailing: commentTexts(text, trailing),\n };\n });\n\n // Comments on their own lines just before `)` go with the last argument.\n const last = result[result.length - 1];\n if (last) {\n const lastArg = args[args.length - 1];\n let from =\n lastArg.getNextSiblingIfKind(SyntaxKind.CommaToken)?.getEnd() ??\n lastArg.getEnd();\n const sameLine = ts.getTrailingCommentRanges(text, from);\n if (sameLine?.length) from = sameLine[sameLine.length - 1].end;\n const dangling = (ts.getLeadingCommentRanges(text, from) ?? []).filter(\n (r) => r.end <= closeParen.getStart(),\n );\n last.trailing.push(...commentTexts(text, dangling));\n }\n return result;\n}\n\nfunction hasComments(list: Piece[]): boolean {\n return list.some((p) => p.leading.length > 0 || p.trailing.length > 0);\n}\n\nfunction renderCall(callee: string, list: Piece[], multiline: boolean): string {\n if (!multiline && !hasComments(list)) {\n return `${callee}(${list.map((p) => p.text).join(\", \")})`;\n }\n const lines = list.map((p) => {\n const leading = p.leading.map((c) => `${c}\\n`).join(\"\");\n const trailing = p.trailing.length ? ` ${p.trailing.join(\" \")}` : \"\";\n return `${leading}${p.text},${trailing}`;\n });\n return `${callee}(\\n${lines.join(\"\\n\")}\\n)`;\n}\n\n/** A lone argument taken out of a nested `sequence`: its comments go above it. */\nfunction renderAlone(piece: Piece): string {\n const comments = [...piece.leading, ...piece.trailing];\n return comments.map((c) => `${c}\\n`).join(\"\") + piece.text;\n}\n\nfunction isMultiline(call: CallExpression): boolean {\n return call\n .getArguments()\n .some((arg, i, args) =>\n i === 0\n ? false\n : arg.getStartLineNumber() !== args[i - 1].getEndLineNumber(),\n );\n}\n\nfunction rewriteSequence(call: CallExpression, list: Piece[]): Node {\n const multiline = isMultiline(call);\n return call.replaceWithText(\n renderCall(call.getExpression().getText(), list, multiline),\n );\n}\n\nfunction handleStatement(site: Site): Statement {\n return site.kind === \"function\" ? site.fn : site.statement;\n}\n\n/** The `handle` statement as it stands now; nodes go stale on every edit. */\nfunction currentStatement(sf: SourceFile): Statement | undefined {\n const located = locate(sf);\n if (\"unsupported\" in located || !located.site) return undefined;\n return handleStatement(located.site);\n}\n\nfunction changed(sf: SourceFile): ComposeResult {\n return { status: \"changed\", statement: currentStatement(sf) };\n}\n\nfunction unchanged(site: Site | null): ComposeResult {\n return {\n status: \"unchanged\",\n statement: site ? handleStatement(site) : undefined,\n };\n}\n\nfunction unsupported(reason: Unsupported): ComposeResult {\n return { status: \"unsupported\", reason };\n}\n\n/**\n * Take the whole `handle` out: its declarator, or its statement with the\n * comments above it, and an `export { handle }` naming it.\n */\nfunction removeWholeHandle(sf: SourceFile, site: Site): void {\n const viaSpecifier = !site.inlineExport;\n if (site.kind === \"variable\" && site.statement.getDeclarations().length > 1) {\n site.decl.remove();\n } else {\n removeStatementWithComments(sf, handleStatement(site));\n }\n if (!viaSpecifier) return;\n for (const ed of sf.getExportDeclarations()) {\n if (ed.getModuleSpecifier() !== undefined) continue;\n const spec = ed.getNamedExports().find((s) => s.getName() === \"handle\");\n if (!spec) continue;\n if (ed.getNamedExports().length === 1) ed.remove();\n else spec.remove();\n }\n}\n\n/**\n * Move a handle that is a function out of the way: rename it `handleApp`,\n * un-export it, and export `sequence(...)` of it right after, so `handleApp`\n * is declared before anything reads it.\n */\nfunction extract(\n sf: SourceFile,\n site: Site,\n spec: HandleSpec,\n callee: string,\n kit: KitSequence,\n): ComposeResult {\n const position = spec.position ?? \"first\";\n const args =\n position === \"first\"\n ? [spec.expression, EXTRACTED]\n : [EXTRACTED, spec.expression];\n const exportKeyword = site.inlineExport ? \"export \" : \"\";\n const composed = `${exportKeyword}const handle = ${callee}(${args.join(\", \")});`;\n\n if (site.kind === \"function\") {\n if (site.inlineExport) site.fn.setIsExported(false);\n sf.getFunctionOrThrow(\"handle\").getNameNode()!.replaceWithText(EXTRACTED);\n const fn = sf.getFunctionOrThrow(EXTRACTED);\n sf.insertText(fn.getEnd(), `\\n\\n${composed}`);\n } else {\n if (site.inlineExport) site.statement.setIsExported(false);\n sf.getVariableDeclarationOrThrow(\"handle\")\n .getNameNode()\n .replaceWithText(EXTRACTED);\n const statement = sf.getVariableStatementOrThrow(EXTRACTED);\n sf.insertText(statement.getEnd(), `\\n\\n${composed}`);\n }\n ensureSequenceImport(sf, kit);\n return changed(sf);\n}\n\n/**\n * After a `sequence` unwraps to `handleApp` alone, put the function back the\n * way `extract` found it: `handleApp` renamed to `handle` and exported, and\n * the `handle = handleApp` statement gone.\n */\nfunction restoreExtracted(sf: SourceFile): void {\n const located = locate(sf);\n if (\"unsupported\" in located || located.site?.kind !== \"variable\") return;\n const { decl, statement, inlineExport } = located.site;\n const init = decl.getInitializer();\n if (\n !init ||\n !Node.isIdentifier(init) ||\n init.getText() !== EXTRACTED ||\n decl.getTypeNode() ||\n statement.getDeclarations().length > 1\n ) {\n return;\n }\n\n const uses = sf\n .getDescendantsOfKind(SyntaxKind.Identifier)\n .filter((id) => id.getText() === EXTRACTED);\n // Its declaration and the one use in `handle`.\n if (uses.length !== 2) return;\n\n const fn = sf.getFunction(EXTRACTED);\n const variable = sf.getVariableStatements().find((s) => {\n const decls = s.getDeclarations();\n return decls.length === 1 && decls[0].getName() === EXTRACTED;\n });\n const target = fn ?? variable;\n if (!target || target.hasExportKeyword()) return;\n\n statement.remove();\n if (fn) {\n const restored = sf.getFunctionOrThrow(EXTRACTED);\n restored.getNameNode()!.replaceWithText(\"handle\");\n if (inlineExport) sf.getFunctionOrThrow(\"handle\").setIsExported(true);\n } else {\n const restored = sf.getVariableDeclarationOrThrow(EXTRACTED);\n restored.getNameNode().replaceWithText(\"handle\");\n if (inlineExport) {\n sf.getVariableStatementOrThrow(\"handle\").setIsExported(true);\n }\n }\n}\n\n/**\n * Add a handle to the exported `handle`. Already present anywhere in the\n * composition: unchanged. No `handle` yet: `export const handle = <expression>`.\n */\nexport function addHandle(sf: SourceFile, spec: HandleSpec): ComposeResult {\n const name = spec.name ?? spec.expression;\n const position = spec.position ?? \"first\";\n const located = locate(sf);\n if (\"unsupported\" in located) return unsupported(located.unsupported);\n const { site } = located;\n const kit = kitSequence(sf);\n\n if (!site) {\n if (located.starExport) return unsupported(\"re-export\");\n const blank = sf.getStatementsWithComments().length > 0 ? \"\\n\" : \"\";\n sf.addStatements(`${blank}export const handle = ${spec.expression};`);\n return changed(sf);\n }\n\n if (site.kind === \"function\") {\n if (references(site.fn, name)) return unsupported(\"ambiguous-reference\");\n return extractChecked(sf, site, spec, kit);\n }\n\n const core = unwrap(site.decl.getInitializerOrThrow());\n if (isHandle(core, name) || findInSequence(core, name, kit)) {\n return unchanged(site);\n }\n if (references(core, name)) return unsupported(\"ambiguous-reference\");\n\n if (isSequenceCall(core, kit)) {\n const list = pieces(core);\n const piece: Piece = { leading: [], text: spec.expression, trailing: [] };\n if (position === \"first\") list.unshift(piece);\n else list.push(piece);\n rewriteSequence(core, list);\n return changed(sf);\n }\n\n if (Node.isArrowFunction(core) || Node.isFunctionExpression(core)) {\n return extractChecked(sf, site, spec, kit);\n }\n\n const callee = sequenceCallee(sf, kit);\n if (!callee) return unsupported(\"foreign-sequence\");\n const existing = core.getText();\n const args =\n position === \"first\"\n ? [spec.expression, existing]\n : [existing, spec.expression];\n const multiline = args.some((a) => a.includes(\"\\n\"));\n core.replaceWithText(\n renderCall(\n callee,\n args.map((text) => ({ leading: [], text, trailing: [] })),\n multiline,\n ),\n );\n ensureSequenceImport(sf, kit);\n return changed(sf);\n}\n\nfunction extractChecked(\n sf: SourceFile,\n site: Site,\n spec: HandleSpec,\n kit: KitSequence,\n): ComposeResult {\n const callee = sequenceCallee(sf, kit);\n if (!callee) return unsupported(\"foreign-sequence\");\n const taken = sf\n .getDescendantsOfKind(SyntaxKind.Identifier)\n .some((id) => id.getText() === EXTRACTED);\n if (taken) return unsupported(\"name-collision\");\n if (site.kind === \"variable\" && site.statement.getDeclarations().length > 1) {\n return unsupported(\"multi-declarator\");\n }\n return extract(sf, site, spec, callee, kit);\n}\n\n/**\n * Take a handle out of the exported `handle`. A `sequence` left with one\n * argument unwraps to it; the last handle takes the `handle` export with it.\n */\nexport function removeHandle(sf: SourceFile, name: string): ComposeResult {\n const located = locate(sf);\n if (\"unsupported\" in located) return unsupported(located.unsupported);\n const { site } = located;\n if (!site) return unchanged(null);\n\n if (site.kind === \"function\") {\n return references(site.fn, name)\n ? unsupported(\"ambiguous-reference\")\n : unchanged(site);\n }\n\n const kit = kitSequence(sf);\n const core = unwrap(site.decl.getInitializerOrThrow());\n if (isHandle(core, name)) {\n removeWholeHandle(sf, site);\n pruneSequenceImport(sf);\n return changed(sf);\n }\n\n const found = findInSequence(core, name, kit);\n if (!found) {\n return references(core, name)\n ? unsupported(\"ambiguous-reference\")\n : unchanged(site);\n }\n\n // Innermost call first; a nested `sequence` emptied by the removal is in\n // turn removed from the one around it.\n const calls = [...found.calls];\n let index = found.index;\n for (;;) {\n const call = calls.pop()!;\n const list = pieces(call);\n list.splice(index, 1);\n const outer = calls[calls.length - 1];\n\n if (list.length === 0) {\n if (!outer) {\n removeWholeHandle(sf, site);\n break;\n }\n index = outer.getArguments().indexOf(call);\n continue;\n }\n if (list.length === 1 && outer) {\n call.replaceWithText(renderAlone(list[0]));\n break;\n }\n if (list.length === 1) {\n // `handle = sequence(x)` unwraps to `handle = x`, and x's comments move\n // above the statement rather than dangle after the `=`.\n const [kept] = list;\n const comments = [...kept.leading, ...kept.trailing];\n call.replaceWithText(kept.text);\n if (comments.length === 0) restoreExtracted(sf);\n else {\n const statement = currentStatement(sf)!;\n sf.insertText(\n statement.getStart(true),\n comments.map((c) => `${c}\\n`).join(\"\"),\n );\n }\n break;\n }\n rewriteSequence(call, list);\n break;\n }\n\n pruneSequenceImport(sf);\n return changed(sf);\n}\n\n/**\n * Swap handle `name` for `spec` in the same place in the chain. When `name`\n * was the whole `handle`, the comments above the statement go too: they\n * described the old handle. With `name` absent this is `addHandle`.\n */\nexport function replaceHandle(\n sf: SourceFile,\n name: string,\n spec: HandleSpec,\n): ComposeResult {\n const newName = spec.name ?? spec.expression;\n const located = locate(sf);\n if (\"unsupported\" in located) return unsupported(located.unsupported);\n const { site } = located;\n if (!site || site.kind === \"function\") return addHandle(sf, spec);\n\n const kit = kitSequence(sf);\n const core = unwrap(site.decl.getInitializerOrThrow());\n if (isHandle(core, newName) || findInSequence(core, newName, kit)) {\n const stale = isHandle(core, name) || findInSequence(core, name, kit);\n return stale ? removeHandle(sf, name) : unchanged(site);\n }\n\n if (isHandle(core, name)) {\n core.replaceWithText(spec.expression);\n removeAttachedComments(sf, sf.getVariableStatementOrThrow(\"handle\"));\n return changed(sf);\n }\n\n const found = findInSequence(core, name, kit);\n if (found) {\n const call = found.calls[found.calls.length - 1];\n const list = pieces(call);\n list[found.index] = { ...list[found.index], text: spec.expression };\n rewriteSequence(call, list);\n return changed(sf);\n }\n if (references(core, name)) return unsupported(\"ambiguous-reference\");\n return addHandle(sf, spec);\n}\n\n/**\n * The handles in the exported `handle`, in order: each argument's identifier,\n * or its callee's, or its source text. A function handle is `handle` itself.\n * `null` when there is no `handle` to compose.\n */\nexport function listHandles(sf: SourceFile): string[] | null {\n const located = locate(sf);\n if (\"unsupported\" in located || !located.site) return null;\n if (located.site.kind === \"function\") return [\"handle\"];\n const kit = kitSequence(sf);\n\n const names = (node: Node): string[] => {\n if (isSequenceCall(node, kit)) return node.getArguments().flatMap(names);\n if (Node.isIdentifier(node)) return [node.getText()];\n if (\n Node.isCallExpression(node) &&\n Node.isIdentifier(node.getExpression())\n ) {\n return [node.getExpression().getText()];\n }\n return [node.getText()];\n };\n return names(unwrap(located.site.decl.getInitializerOrThrow()));\n}\n"],"mappings":";;;AAiCA,IAAM,IAAY,uBACZ,IAAY;AA+DlB,SAAS,EAAO,GAAyB;CACvC,IAAI,IAAsB,IACtB,IAAa;CAEjB,KAAK,IAAM,KAAM,EAAG,sBAAsB,GAAG;EAC3C,IAAM,IAAa,EAAG,mBAAmB,MAAM,KAAA;EAC/C,IAAI,EAAG,kBAAkB,GAAG;GAC1B,IAAI,EAAG,mBAAmB,CAAC,EAAE,QAAQ,MAAM,UACzC,OAAO,EAAE,aAAa,YAAY;GAEpC,AAAI,MAAY,IAAa;GAC7B;EACF;EACA,KAAK,IAAM,KAAQ,EAAG,gBAAgB,GAEpC,KADiB,EAAK,aAAa,CAAC,EAAE,QAAQ,KAAK,EAAK,QAAQ,OAC/C,UACjB;OAAI,KAAc,EAAK,QAAQ,MAAM,UACnC,OAAO,EAAE,aAAa,YAAY;GAEpC,IAAsB;EAFc;CAIxC;CAEA,IAAM,IAAK,EAAG,aAAa,CAAC,CAAC,MAAM,MAAM,EAAE,QAAQ,MAAM,QAAQ;CACjE,IAAI,GAKF,OAJI,EAAG,gBAAgB,IAAU,EAAE,aAAa,iBAAiB,IAC7D,CAAC,EAAG,iBAAiB,KAAK,CAAC,IACtB,EAAE,aAAa,eAAe,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AAO,EAAU,GAAI,CAAI;CAEhE,IAAM,IAAM,EAAY,CAAE,GACpB,IAAO,EAAO,EAAK,KAAK,sBAAsB,CAAC;CACrD,IAAI,EAAS,GAAM,CAAO,KAAK,EAAe,GAAM,GAAS,CAAG,GAE9D,OADc,EAAS,GAAM,CAAI,KAAK,EAAe,GAAM,GAAM,CAAG,IACrD,EAAa,GAAI,CAAI,IAAI,EAAU,CAAI;CAGxD,IAAI,EAAS,GAAM,CAAI,GAGrB,OAFA,EAAK,gBAAgB,EAAK,UAAU,GACpC,EAAuB,GAAI,EAAG,4BAA4B,QAAQ,CAAC,GAC5D,EAAQ,CAAE;CAGnB,IAAM,IAAQ,EAAe,GAAM,GAAM,CAAG;CAC5C,IAAI,GAAO;EACT,IAAM,IAAO,EAAM,MAAM,EAAM,MAAM,SAAS,IACxC,IAAO,EAAO,CAAI;EAGxB,OAFA,EAAK,EAAM,SAAS;GAAE,GAAG,EAAK,EAAM;GAAQ,MAAM,EAAK;EAAW,GAClE,EAAgB,GAAM,CAAI,GACnB,EAAQ,CAAE;CACnB;CAEA,OADI,EAAW,GAAM,CAAI,IAAU,EAAY,qBAAqB,IAC7D,EAAU,GAAI,CAAI;AAC3B"}
1
+ {"version":3,"file":"compose-handle-B-CkDcQD.js","names":[],"sources":["../../src/runtime/compose-handle.ts"],"sourcesContent":["import {\n Node,\n SyntaxKind,\n ts,\n type CallExpression,\n type Expression,\n type FunctionDeclaration,\n type SourceFile,\n type Statement,\n type VariableDeclaration,\n type VariableStatement,\n} from \"ts-morph\";\nimport {\n ensureBlankLineAfterImports,\n removeAttachedComments,\n removeNamedImportIfUnused,\n removeStatementWithComments,\n} from \"./ts-morph-helpers\";\n\n/**\n * Composes the server `handle` hook in `hooks.server.ts`.\n *\n * Patterns add and subtract handles in the exported `handle` without caring\n * what shape it is in: a lone expression becomes `sequence(new, old)`, a\n * `sequence(...)` gains or loses an argument, and a handle that is a function\n * is moved to a local `handleApp` so it can take part. Subtracting back to one\n * handle unwraps the `sequence` again, and puts a `handleApp` back the way it\n * was written, so enabling then disabling a pattern round-trips.\n *\n * Nothing here formats or saves: callers do, as they always have. A result of\n * `unsupported` means the file was left exactly as it was found.\n */\n\nconst KIT_HOOKS = \"@sveltejs/kit/hooks\";\nconst EXTRACTED = \"handleApp\";\n\nexport interface HandleSpec {\n /** Source text of the sequence argument: `handleWuchale`, `handlePocketbase({ ... })`. */\n expression: string;\n /** Identifier, or callee identifier, that marks this handle. Defaults to `expression`. */\n name?: string;\n /** Where it goes in the chain. */\n position?: \"first\" | \"last\";\n}\n\nexport type Unsupported =\n /** `export { handle } from '…'`, `export { x as handle }`, or `export *` with no local handle. */\n | \"re-export\"\n /** A local `handle` SvelteKit cannot see. */\n | \"not-exported\"\n /** `export const { handle } = …` */\n | \"destructured\"\n /** `export default function handle` */\n | \"default-export\"\n /** `export let handle;` */\n | \"no-initializer\"\n /** A `sequence` in scope that is not `@sveltejs/kit/hooks`'. */\n | \"foreign-sequence\"\n /** The handle has to move to `handleApp`, and the name is taken. */\n | \"name-collision\"\n /** The handle has to move to `handleApp`, and shares its statement with other declarations. */\n | \"multi-declarator\"\n /** The handle is referenced outside the composition (`dev ? a : handleX`, or inside a function handle). */\n | \"ambiguous-reference\";\n\nexport type ComposeResult =\n /** `statement` is the `handle` declaration, when there still is one. */\n | { status: \"changed\"; statement?: Statement }\n | { status: \"unchanged\"; statement?: Statement }\n | { status: \"unsupported\"; reason: Unsupported };\n\ntype Site =\n | {\n kind: \"variable\";\n decl: VariableDeclaration;\n statement: VariableStatement;\n inlineExport: boolean;\n }\n | { kind: \"function\"; fn: FunctionDeclaration; inlineExport: boolean };\n\ntype Located =\n { site: Site | null; starExport: boolean } | { unsupported: Unsupported };\n\n/** A `sequence(...)` argument with the comments that belong to it. */\ninterface Piece {\n leading: string[];\n text: string;\n trailing: string[];\n}\n\n/** How `sequence` from `@sveltejs/kit/hooks` is bound in this file, if at all. */\ninterface KitSequence {\n local: string | null;\n namespace: string | null;\n}\n\n/** Find the exported `handle`, or say why it cannot be composed. */\nfunction locate(sf: SourceFile): Located {\n let exportedBySpecifier = false;\n let starExport = false;\n\n for (const ed of sf.getExportDeclarations()) {\n const fromModule = ed.getModuleSpecifier() !== undefined;\n if (ed.isNamespaceExport()) {\n if (ed.getNamespaceExport()?.getName() === \"handle\") {\n return { unsupported: \"re-export\" };\n }\n if (fromModule) starExport = true;\n continue;\n }\n for (const spec of ed.getNamedExports()) {\n const exported = spec.getAliasNode()?.getText() ?? spec.getName();\n if (exported !== \"handle\") continue;\n if (fromModule || spec.getName() !== \"handle\") {\n return { unsupported: \"re-export\" };\n }\n exportedBySpecifier = true;\n }\n }\n\n const fn = sf.getFunctions().find((f) => f.getName() === \"handle\");\n if (fn) {\n if (fn.isDefaultExport()) return { unsupported: \"default-export\" };\n if (!fn.hasExportKeyword() && !exportedBySpecifier) {\n return { unsupported: \"not-exported\" };\n }\n return {\n site: { kind: \"function\", fn, inlineExport: fn.hasExportKeyword() },\n starExport,\n };\n }\n\n for (const statement of sf.getVariableStatements()) {\n for (const decl of statement.getDeclarations()) {\n const nameNode = decl.getNameNode();\n if (!Node.isIdentifier(nameNode)) {\n const bindsHandle = nameNode\n .getDescendantsOfKind(SyntaxKind.BindingElement)\n .some((el) => el.getNameNode().getText() === \"handle\");\n if (bindsHandle) return { unsupported: \"destructured\" };\n continue;\n }\n if (nameNode.getText() !== \"handle\") continue;\n if (!statement.hasExportKeyword() && !exportedBySpecifier) {\n return { unsupported: \"not-exported\" };\n }\n if (!decl.getInitializer()) return { unsupported: \"no-initializer\" };\n return {\n site: {\n kind: \"variable\",\n decl,\n statement,\n inlineExport: statement.hasExportKeyword(),\n },\n starExport,\n };\n }\n }\n\n // `export { handle }` naming something that is not a local variable or\n // function: an import passed straight through, or a class.\n if (exportedBySpecifier) return { unsupported: \"re-export\" };\n return { site: null, starExport };\n}\n\nfunction kitSequence(sf: SourceFile): KitSequence {\n const found: KitSequence = { local: null, namespace: null };\n for (const decl of sf.getImportDeclarations()) {\n if (decl.getModuleSpecifierValue() !== KIT_HOOKS || decl.isTypeOnly()) {\n continue;\n }\n const namespace = decl.getNamespaceImport();\n if (namespace) found.namespace = namespace.getText();\n for (const named of decl.getNamedImports()) {\n if (named.getName() !== \"sequence\" || named.isTypeOnly()) continue;\n found.local = named.getAliasNode()?.getText() ?? \"sequence\";\n }\n }\n return found;\n}\n\n/** Whether `name` is declared at the top level or imported. */\nfunction isBound(sf: SourceFile, name: string): boolean {\n for (const decl of sf.getImportDeclarations()) {\n if (decl.getDefaultImport()?.getText() === name) return true;\n if (decl.getNamespaceImport()?.getText() === name) return true;\n for (const named of decl.getNamedImports()) {\n if ((named.getAliasNode()?.getText() ?? named.getName()) === name) {\n return true;\n }\n }\n }\n if (sf.getFunction(name) || sf.getClass(name) || sf.getEnum(name)) {\n return true;\n }\n return sf.getVariableDeclarations().some((d) => {\n const nameNode = d.getNameNode();\n if (Node.isIdentifier(nameNode)) return nameNode.getText() === name;\n return nameNode\n .getDescendantsOfKind(SyntaxKind.BindingElement)\n .some((el) => el.getNameNode().getText() === name);\n });\n}\n\n/** The callee to write for a new `sequence(...)`, or null when none can be had. */\nfunction sequenceCallee(sf: SourceFile, kit: KitSequence): string | null {\n if (kit.local) return kit.local;\n if (kit.namespace) return `${kit.namespace}.sequence`;\n return isBound(sf, \"sequence\") ? null : \"sequence\";\n}\n\nfunction ensureSequenceImport(sf: SourceFile, kit: KitSequence): void {\n if (kit.local || kit.namespace) return;\n const decl = sf\n .getImportDeclarations()\n .find(\n (d) =>\n d.getModuleSpecifierValue() === KIT_HOOKS &&\n !d.isTypeOnly() &&\n !d.getNamespaceImport(),\n );\n if (decl) decl.addNamedImport(\"sequence\");\n else {\n sf.addImportDeclaration({\n namedImports: [\"sequence\"],\n moduleSpecifier: KIT_HOOKS,\n });\n }\n}\n\nfunction pruneSequenceImport(sf: SourceFile): void {\n // ts-morph takes the blank line after the imports with a removed import.\n const { wasRemoved } = removeNamedImportIfUnused(sf, KIT_HOOKS, \"sequence\");\n if (wasRemoved) ensureBlankLineAfterImports(sf);\n}\n\nfunction isSequenceCall(node: Node, kit: KitSequence): node is CallExpression {\n if (!Node.isCallExpression(node)) return false;\n const callee = node.getExpression();\n if (Node.isIdentifier(callee)) return callee.getText() === kit.local;\n if (Node.isPropertyAccessExpression(callee)) {\n return (\n kit.namespace !== null &&\n callee.getExpression().getText() === kit.namespace &&\n callee.getName() === \"sequence\"\n );\n }\n return false;\n}\n\n/** Strip `( )`, `satisfies T`, `as T`, `<T>` and `!` down to the composition. */\nfunction unwrap(node: Expression): Expression {\n for (;;) {\n if (\n Node.isParenthesizedExpression(node) ||\n Node.isSatisfiesExpression(node) ||\n Node.isAsExpression(node) ||\n Node.isTypeAssertion(node) ||\n Node.isNonNullExpression(node)\n ) {\n node = node.getExpression();\n } else {\n return node;\n }\n }\n}\n\n/** `name`, or a call of `name`: `handleWuchale`, `handlePocketbase({ ... })`. */\nfunction isHandle(node: Node, name: string): boolean {\n if (Node.isIdentifier(node)) return node.getText() === name;\n if (Node.isCallExpression(node)) {\n const callee = node.getExpression();\n return Node.isIdentifier(callee) && callee.getText() === name;\n }\n return false;\n}\n\n/** The chain of `sequence` calls down to the argument that is `name`. */\nfunction findInSequence(\n node: Node,\n name: string,\n kit: KitSequence,\n): { calls: CallExpression[]; index: number } | null {\n if (!isSequenceCall(node, kit)) return null;\n const args = node.getArguments();\n const index = args.findIndex((arg) => isHandle(arg, name));\n if (index >= 0) return { calls: [node], index };\n for (const arg of args) {\n const inner = findInSequence(arg, name, kit);\n if (inner) return { calls: [node, ...inner.calls], index: inner.index };\n }\n return null;\n}\n\nfunction references(node: Node, name: string): boolean {\n if (Node.isIdentifier(node) && node.getText() === name) return true;\n return node\n .getDescendantsOfKind(SyntaxKind.Identifier)\n .some((id) => id.getText() === name);\n}\n\nfunction commentTexts(text: string, ranges: ts.CommentRange[]): string[] {\n return ranges.map((r) => text.slice(r.pos, r.end));\n}\n\n/**\n * The arguments of a `sequence(...)` call, each with its comments. A comment\n * after an argument's comma on the same line is that argument's; comments on\n * the lines above an argument are its own too.\n */\nfunction pieces(call: CallExpression): Piece[] {\n const text = call.getSourceFile().getFullText();\n const args = call.getArguments();\n const openParen = call.getFirstChildByKindOrThrow(SyntaxKind.OpenParenToken);\n const closeParen = call.getLastChildByKindOrThrow(SyntaxKind.CloseParenToken);\n\n const result = args.map((arg, i): Piece => {\n let leadingFrom = openParen.getEnd();\n if (i > 0) {\n const prevComma = args[i - 1].getNextSiblingIfKind(SyntaxKind.CommaToken);\n leadingFrom = prevComma?.getEnd() ?? args[i - 1].getEnd();\n const prevTrailing = ts.getTrailingCommentRanges(text, leadingFrom);\n if (prevTrailing?.length) {\n leadingFrom = prevTrailing[prevTrailing.length - 1].end;\n }\n }\n const leading = (\n ts.getLeadingCommentRanges(text, leadingFrom) ?? []\n ).filter((r) => r.end <= arg.getStart());\n const comma = arg.getNextSiblingIfKind(SyntaxKind.CommaToken);\n const trailing =\n ts.getTrailingCommentRanges(text, comma?.getEnd() ?? arg.getEnd()) ?? [];\n return {\n leading: commentTexts(text, leading),\n text: arg.getText(),\n trailing: commentTexts(text, trailing),\n };\n });\n\n // Comments on their own lines just before `)` go with the last argument.\n const last = result[result.length - 1];\n if (last) {\n const lastArg = args[args.length - 1];\n let from =\n lastArg.getNextSiblingIfKind(SyntaxKind.CommaToken)?.getEnd() ??\n lastArg.getEnd();\n const sameLine = ts.getTrailingCommentRanges(text, from);\n if (sameLine?.length) from = sameLine[sameLine.length - 1].end;\n const dangling = (ts.getLeadingCommentRanges(text, from) ?? []).filter(\n (r) => r.end <= closeParen.getStart(),\n );\n last.trailing.push(...commentTexts(text, dangling));\n }\n return result;\n}\n\nfunction hasComments(list: Piece[]): boolean {\n return list.some((p) => p.leading.length > 0 || p.trailing.length > 0);\n}\n\nfunction renderCall(callee: string, list: Piece[], multiline: boolean): string {\n if (!multiline && !hasComments(list)) {\n return `${callee}(${list.map((p) => p.text).join(\", \")})`;\n }\n const lines = list.map((p) => {\n const leading = p.leading.map((c) => `${c}\\n`).join(\"\");\n const trailing = p.trailing.length ? ` ${p.trailing.join(\" \")}` : \"\";\n return `${leading}${p.text},${trailing}`;\n });\n return `${callee}(\\n${lines.join(\"\\n\")}\\n)`;\n}\n\n/** A lone argument taken out of a nested `sequence`: its comments go above it. */\nfunction renderAlone(piece: Piece): string {\n const comments = [...piece.leading, ...piece.trailing];\n return comments.map((c) => `${c}\\n`).join(\"\") + piece.text;\n}\n\nfunction isMultiline(call: CallExpression): boolean {\n return call\n .getArguments()\n .some((arg, i, args) =>\n i === 0\n ? false\n : arg.getStartLineNumber() !== args[i - 1].getEndLineNumber(),\n );\n}\n\nfunction rewriteSequence(call: CallExpression, list: Piece[]): Node {\n const multiline = isMultiline(call);\n return call.replaceWithText(\n renderCall(call.getExpression().getText(), list, multiline),\n );\n}\n\nfunction handleStatement(site: Site): Statement {\n return site.kind === \"function\" ? site.fn : site.statement;\n}\n\n/** The `handle` statement as it stands now; nodes go stale on every edit. */\nfunction currentStatement(sf: SourceFile): Statement | undefined {\n const located = locate(sf);\n if (\"unsupported\" in located || !located.site) return undefined;\n return handleStatement(located.site);\n}\n\nfunction changed(sf: SourceFile): ComposeResult {\n return { status: \"changed\", statement: currentStatement(sf) };\n}\n\nfunction unchanged(site: Site | null): ComposeResult {\n return {\n status: \"unchanged\",\n statement: site ? handleStatement(site) : undefined,\n };\n}\n\nfunction unsupported(reason: Unsupported): ComposeResult {\n return { status: \"unsupported\", reason };\n}\n\n/**\n * Take the whole `handle` out: its declarator, or its statement with the\n * comments above it, and an `export { handle }` naming it.\n */\nfunction removeWholeHandle(sf: SourceFile, site: Site): void {\n const viaSpecifier = !site.inlineExport;\n if (site.kind === \"variable\" && site.statement.getDeclarations().length > 1) {\n site.decl.remove();\n } else {\n removeStatementWithComments(sf, handleStatement(site));\n }\n if (!viaSpecifier) return;\n for (const ed of sf.getExportDeclarations()) {\n if (ed.getModuleSpecifier() !== undefined) continue;\n const spec = ed.getNamedExports().find((s) => s.getName() === \"handle\");\n if (!spec) continue;\n if (ed.getNamedExports().length === 1) ed.remove();\n else spec.remove();\n }\n}\n\n/**\n * Move a handle that is a function out of the way: rename it `handleApp`,\n * un-export it, and export `sequence(...)` of it right after, so `handleApp`\n * is declared before anything reads it.\n */\nfunction extract(\n sf: SourceFile,\n site: Site,\n spec: HandleSpec,\n callee: string,\n kit: KitSequence,\n): ComposeResult {\n const position = spec.position ?? \"first\";\n const args =\n position === \"first\"\n ? [spec.expression, EXTRACTED]\n : [EXTRACTED, spec.expression];\n const exportKeyword = site.inlineExport ? \"export \" : \"\";\n const composed = `${exportKeyword}const handle = ${callee}(${args.join(\", \")});`;\n\n if (site.kind === \"function\") {\n if (site.inlineExport) site.fn.setIsExported(false);\n sf.getFunctionOrThrow(\"handle\").getNameNode()!.replaceWithText(EXTRACTED);\n const fn = sf.getFunctionOrThrow(EXTRACTED);\n sf.insertText(fn.getEnd(), `\\n\\n${composed}`);\n } else {\n if (site.inlineExport) site.statement.setIsExported(false);\n sf.getVariableDeclarationOrThrow(\"handle\")\n .getNameNode()\n .replaceWithText(EXTRACTED);\n const statement = sf.getVariableStatementOrThrow(EXTRACTED);\n sf.insertText(statement.getEnd(), `\\n\\n${composed}`);\n }\n ensureSequenceImport(sf, kit);\n return changed(sf);\n}\n\n/**\n * After a `sequence` unwraps to `handleApp` alone, put the function back the\n * way `extract` found it: `handleApp` renamed to `handle` and exported, and\n * the `handle = handleApp` statement gone.\n */\nfunction restoreExtracted(sf: SourceFile): void {\n const located = locate(sf);\n if (\"unsupported\" in located || located.site?.kind !== \"variable\") return;\n const { decl, statement, inlineExport } = located.site;\n const init = decl.getInitializer();\n if (\n !init ||\n !Node.isIdentifier(init) ||\n init.getText() !== EXTRACTED ||\n decl.getTypeNode() ||\n statement.getDeclarations().length > 1\n ) {\n return;\n }\n\n const uses = sf\n .getDescendantsOfKind(SyntaxKind.Identifier)\n .filter((id) => id.getText() === EXTRACTED);\n // Its declaration and the one use in `handle`.\n if (uses.length !== 2) return;\n\n const fn = sf.getFunction(EXTRACTED);\n const variable = sf.getVariableStatements().find((s) => {\n const decls = s.getDeclarations();\n return decls.length === 1 && decls[0].getName() === EXTRACTED;\n });\n const target = fn ?? variable;\n if (!target || target.hasExportKeyword()) return;\n\n statement.remove();\n if (fn) {\n const restored = sf.getFunctionOrThrow(EXTRACTED);\n restored.getNameNode()!.replaceWithText(\"handle\");\n if (inlineExport) sf.getFunctionOrThrow(\"handle\").setIsExported(true);\n } else {\n const restored = sf.getVariableDeclarationOrThrow(EXTRACTED);\n restored.getNameNode().replaceWithText(\"handle\");\n if (inlineExport) {\n sf.getVariableStatementOrThrow(\"handle\").setIsExported(true);\n }\n }\n}\n\n/**\n * Add a handle to the exported `handle`. Already present anywhere in the\n * composition: unchanged. No `handle` yet: `export const handle = <expression>`.\n */\nexport function addHandle(sf: SourceFile, spec: HandleSpec): ComposeResult {\n const name = spec.name ?? spec.expression;\n const position = spec.position ?? \"first\";\n const located = locate(sf);\n if (\"unsupported\" in located) return unsupported(located.unsupported);\n const { site } = located;\n const kit = kitSequence(sf);\n\n if (!site) {\n if (located.starExport) return unsupported(\"re-export\");\n const blank = sf.getStatementsWithComments().length > 0 ? \"\\n\" : \"\";\n sf.addStatements(`${blank}export const handle = ${spec.expression};`);\n return changed(sf);\n }\n\n if (site.kind === \"function\") {\n if (references(site.fn, name)) return unsupported(\"ambiguous-reference\");\n return extractChecked(sf, site, spec, kit);\n }\n\n const core = unwrap(site.decl.getInitializerOrThrow());\n if (isHandle(core, name) || findInSequence(core, name, kit)) {\n return unchanged(site);\n }\n if (references(core, name)) return unsupported(\"ambiguous-reference\");\n\n if (isSequenceCall(core, kit)) {\n const list = pieces(core);\n const piece: Piece = { leading: [], text: spec.expression, trailing: [] };\n if (position === \"first\") list.unshift(piece);\n else list.push(piece);\n rewriteSequence(core, list);\n return changed(sf);\n }\n\n if (Node.isArrowFunction(core) || Node.isFunctionExpression(core)) {\n return extractChecked(sf, site, spec, kit);\n }\n\n const callee = sequenceCallee(sf, kit);\n if (!callee) return unsupported(\"foreign-sequence\");\n const existing = core.getText();\n const args =\n position === \"first\"\n ? [spec.expression, existing]\n : [existing, spec.expression];\n const multiline = args.some((a) => a.includes(\"\\n\"));\n core.replaceWithText(\n renderCall(\n callee,\n args.map((text) => ({ leading: [], text, trailing: [] })),\n multiline,\n ),\n );\n ensureSequenceImport(sf, kit);\n return changed(sf);\n}\n\nfunction extractChecked(\n sf: SourceFile,\n site: Site,\n spec: HandleSpec,\n kit: KitSequence,\n): ComposeResult {\n const callee = sequenceCallee(sf, kit);\n if (!callee) return unsupported(\"foreign-sequence\");\n const taken = sf\n .getDescendantsOfKind(SyntaxKind.Identifier)\n .some((id) => id.getText() === EXTRACTED);\n if (taken) return unsupported(\"name-collision\");\n if (site.kind === \"variable\" && site.statement.getDeclarations().length > 1) {\n return unsupported(\"multi-declarator\");\n }\n return extract(sf, site, spec, callee, kit);\n}\n\n/**\n * Take a handle out of the exported `handle`. A `sequence` left with one\n * argument unwraps to it; the last handle takes the `handle` export with it.\n */\nexport function removeHandle(sf: SourceFile, name: string): ComposeResult {\n const located = locate(sf);\n if (\"unsupported\" in located) return unsupported(located.unsupported);\n const { site } = located;\n if (!site) return unchanged(null);\n\n if (site.kind === \"function\") {\n return references(site.fn, name)\n ? unsupported(\"ambiguous-reference\")\n : unchanged(site);\n }\n\n const kit = kitSequence(sf);\n const core = unwrap(site.decl.getInitializerOrThrow());\n if (isHandle(core, name)) {\n removeWholeHandle(sf, site);\n pruneSequenceImport(sf);\n return changed(sf);\n }\n\n const found = findInSequence(core, name, kit);\n if (!found) {\n return references(core, name)\n ? unsupported(\"ambiguous-reference\")\n : unchanged(site);\n }\n\n // Innermost call first; a nested `sequence` emptied by the removal is in\n // turn removed from the one around it.\n const calls = [...found.calls];\n let index = found.index;\n for (;;) {\n const call = calls.pop()!;\n const list = pieces(call);\n list.splice(index, 1);\n const outer = calls[calls.length - 1];\n\n if (list.length === 0) {\n if (!outer) {\n removeWholeHandle(sf, site);\n break;\n }\n index = outer.getArguments().indexOf(call);\n continue;\n }\n if (list.length === 1 && outer) {\n call.replaceWithText(renderAlone(list[0]));\n break;\n }\n if (list.length === 1) {\n // `handle = sequence(x)` unwraps to `handle = x`, and x's comments move\n // above the statement rather than dangle after the `=`.\n const [kept] = list;\n const comments = [...kept.leading, ...kept.trailing];\n call.replaceWithText(kept.text);\n if (comments.length === 0) restoreExtracted(sf);\n else {\n const statement = currentStatement(sf)!;\n sf.insertText(\n statement.getStart(true),\n comments.map((c) => `${c}\\n`).join(\"\"),\n );\n }\n break;\n }\n rewriteSequence(call, list);\n break;\n }\n\n pruneSequenceImport(sf);\n return changed(sf);\n}\n\n/**\n * Swap handle `name` for `spec` in the same place in the chain. When `name`\n * was the whole `handle`, the comments above the statement go too: they\n * described the old handle. With `name` absent this is `addHandle`.\n */\nexport function replaceHandle(\n sf: SourceFile,\n name: string,\n spec: HandleSpec,\n): ComposeResult {\n const newName = spec.name ?? spec.expression;\n const located = locate(sf);\n if (\"unsupported\" in located) return unsupported(located.unsupported);\n const { site } = located;\n if (!site || site.kind === \"function\") return addHandle(sf, spec);\n\n const kit = kitSequence(sf);\n const core = unwrap(site.decl.getInitializerOrThrow());\n if (isHandle(core, newName) || findInSequence(core, newName, kit)) {\n const stale = isHandle(core, name) || findInSequence(core, name, kit);\n return stale ? removeHandle(sf, name) : unchanged(site);\n }\n\n if (isHandle(core, name)) {\n core.replaceWithText(spec.expression);\n removeAttachedComments(sf, sf.getVariableStatementOrThrow(\"handle\"));\n return changed(sf);\n }\n\n const found = findInSequence(core, name, kit);\n if (found) {\n const call = found.calls[found.calls.length - 1];\n const list = pieces(call);\n list[found.index] = { ...list[found.index], text: spec.expression };\n rewriteSequence(call, list);\n return changed(sf);\n }\n if (references(core, name)) return unsupported(\"ambiguous-reference\");\n return addHandle(sf, spec);\n}\n\n/**\n * The handles in the exported `handle`, in order: each argument's identifier,\n * or its callee's, or its source text. A function handle is `handle` itself.\n * `null` when there is no `handle` to compose.\n */\nexport function listHandles(sf: SourceFile): string[] | null {\n const located = locate(sf);\n if (\"unsupported\" in located || !located.site) return null;\n if (located.site.kind === \"function\") return [\"handle\"];\n const kit = kitSequence(sf);\n\n const names = (node: Node): string[] => {\n if (isSequenceCall(node, kit)) return node.getArguments().flatMap(names);\n if (Node.isIdentifier(node)) return [node.getText()];\n if (\n Node.isCallExpression(node) &&\n Node.isIdentifier(node.getExpression())\n ) {\n return [node.getExpression().getText()];\n }\n return [node.getText()];\n };\n return names(unwrap(located.site.decl.getInitializerOrThrow()));\n}\n"],"mappings":";;;AAiCA,IAAM,IAAY,uBACZ,IAAY;AA+DlB,SAAS,EAAO,GAAyB;CACvC,IAAI,IAAsB,IACtB,IAAa;CAEjB,KAAK,IAAM,KAAM,EAAG,sBAAsB,GAAG;EAC3C,IAAM,IAAa,EAAG,mBAAmB,MAAM,KAAA;EAC/C,IAAI,EAAG,kBAAkB,GAAG;GAC1B,IAAI,EAAG,mBAAmB,CAAC,EAAE,QAAQ,MAAM,UACzC,OAAO,EAAE,aAAa,YAAY;GAEpC,AAAI,MAAY,IAAa;GAC7B;EACF;EACA,KAAK,IAAM,KAAQ,EAAG,gBAAgB,GAEpC,KADiB,EAAK,aAAa,CAAC,EAAE,QAAQ,KAAK,EAAK,QAAQ,OAC/C,UACjB;OAAI,KAAc,EAAK,QAAQ,MAAM,UACnC,OAAO,EAAE,aAAa,YAAY;GAEpC,IAAsB;EAFc;CAIxC;CAEA,IAAM,IAAK,EAAG,aAAa,CAAC,CAAC,MAAM,MAAM,EAAE,QAAQ,MAAM,QAAQ;CACjE,IAAI,GAKF,OAJI,EAAG,gBAAgB,IAAU,EAAE,aAAa,iBAAiB,IAC7D,CAAC,EAAG,iBAAiB,KAAK,CAAC,IACtB,EAAE,aAAa,eAAe,IAEhC;EACL,MAAM;GAAE,MAAM;GAAY;GAAI,cAAc,EAAG,iBAAiB;EAAE;EAClE;CACF;CAGF,KAAK,IAAM,K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