@tolki/ts 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Abraham Arango
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,316 @@
1
+ <p align="center"><img src="https://raw.githubusercontent.com/abetwothree/tolki/refs/heads/master/docs/vitepress/public/tolki-logo-short.svg" width="50%" alt="Laravel Tolki JS Logo"></p>
2
+
3
+ # Tolki JS TypeScript Package
4
+
5
+ This package provides TypeScript utility functions meant to be used by the [Laravel TypeScript Publisher](https://github.com/abetwothree/laravel-ts-publish/) PHP Package.
6
+
7
+ Features currently include the following:
8
+
9
+ - TypeScript Enum support with similar functionality to a PHP enum.
10
+ - TypeScript Route support to use Laravel's route definitions in frontend projects.
11
+ - A supporting Vite plugin to automatically publish files on production builds and automatically update TypeScript definitions on PHP file changes during development.
12
+
13
+ ## Documentation
14
+
15
+ The full documentation for the enum utilities can be found at [https://tolki.abe.dev](https://tolki.abe.dev/ts/).
16
+
17
+ <!-- AUTO-GENERATED-DOCS:START -->
18
+
19
+ ## TypeScript Utilities Installation
20
+
21
+ The [`@tolki/ts`](https://www.npmjs.com/package/@tolki/ts) package provides a variety of enum manipulation utilities inspired by PHP's enum utilities like [from](https://www.php.net/manual/en/backedenum.from.php), [tryFrom](https://www.php.net/manual/en/backedenum.tryfrom.php), and [cases](https://www.php.net/manual/en/unitenum.cases.php).
22
+
23
+ This package is meant to be used with the [Laravel TypeScript Publisher](https://github.com/abetwothree/laravel-ts-publish), which transforms PHP enums & routes into functional TypeScript objects.
24
+
25
+ The `@tolki/ts` package provides utilities to work with these TypeScript enums in a way that is similar to how you would work with PHP enums in Laravel. It also provides a `defineRoute` utility factory function to work with Laravel defined routes on the frontend.
26
+
27
+ You can install this package via npm, yarn, or pnpm:
28
+
29
+ ```bash [npm]
30
+ npm install @tolki/ts
31
+ ```
32
+
33
+ ```bash [yarn]
34
+ yarn add @tolki/ts
35
+ ```
36
+
37
+ ```bash [pnpm]
38
+ pnpm add @tolki/ts
39
+ ```
40
+
41
+ ## Tolki Enum Utilities List
42
+
43
+ ### Enum Utilities List
44
+
45
+ As mentioned in the [Enum Utilities Installation](./index.md) page, the `@tolki/ts` package is not meant to be used as standalone package as it works with the [Laravel TypeScript Publisher](https://github.com/abetwothree/laravel-ts-publish) package to transform PHP enums into TypeScript enums. The functions below are being listed out for reference, not necessarily for direct use.
46
+
47
+ [cases](#cases) [defineEnum](#defineenum) [from](#from) [tryFrom](#tryfrom)
48
+
49
+ ### Enum Utilities Details
50
+
51
+ #### cases
52
+
53
+ Similar to the PHP [cases](https://www.php.net/manual/en/unitenum.cases.php) method, this function returns an array of all the cases of the given enum.
54
+
55
+ ```javascript
56
+ import { cases } from "@tolki/ts";
57
+ import { Status } from "@js/types/enums";
58
+
59
+ const result = cases(Status); // result is an array with an enum instance for each case in the Status enum
60
+ ```
61
+
62
+ #### defineEnum
63
+
64
+ This is a factory function that is automatically applied by the Laravel TypeScript Publisher package when it transforms PHP enums into TypeScript enums. It automatically adds the `cases`, `from`, and `tryFrom` methods to the transformed TypeScript enums.
65
+
66
+ ```javascript
67
+ import { defineEnum } from "@tolki/ts";
68
+
69
+ const Status = defineEnum({
70
+ ACTIVE: "active",
71
+ INACTIVE: "inactive",
72
+ PENDING: "pending",
73
+ // automatically added by the Laravel TypeScript Publisher package
74
+ _cases: ["ACTIVE", "INACTIVE", "PENDING"],
75
+ _methods: [],
76
+ _static: [],
77
+ });
78
+
79
+ Status.cases(); // result is an array with an enum instance for each case in the Status enum
80
+ Status.from("active"); // result is the enum instance for the ACTIVE case
81
+ Status.tryFrom("non-valid-key"); // result null
82
+ ```
83
+
84
+ #### from
85
+
86
+ Similar to the PHP [from](https://www.php.net/manual/en/backedenum.from.php) method, this function returns the enum instance for the given value. If the value does not exist in the enum, it throws an error.
87
+
88
+ ```javascript
89
+ import { from } from "@tolki/ts";
90
+ import { Status } from "@js/types/enums";
91
+
92
+ const result = from(Status, "active"); // result is the enum instance for the ACTIVE case
93
+ const result2 = from(Status, "non-valid-key"); // throws an error because "non-valid-key" is not a valid value
94
+ ```
95
+
96
+ #### tryFrom
97
+
98
+ Similar to the PHP [tryFrom](https://www.php.net/manual/en/backedenum.tryfrom.php) method, this function returns the enum instance for the given value. If the value does not exist in the enum, it returns null instead of throwing an error.
99
+
100
+ ```javascript
101
+ import { tryFrom } from "@tolki/ts";
102
+ import { Status } from "@js/types/enums";
103
+
104
+ const result = tryFrom(Status, "active"); // result is the enum instance for the ACTIVE case
105
+ const result2 = tryFrom(Status, "non-valid-key"); // result is null because "non-valid-key" is not a valid value
106
+ ```
107
+
108
+ ## Tolki Enum Laravel TypeScript Publisher Vite Plugin
109
+
110
+ The `@tolki/ts` package provides a Vite plugin to automatically watch for changes of the transformed PHP files by the [Laravel TypeScript Publisher](https://github.com/abetwothree/laravel-ts-publish) package.
111
+
112
+ The Laravel TypeScript Publisher package can publish a JSON file list of transformed PHP files. This Vite plugin uses that JSON file list to watch for changes in those PHP files and automatically call the `php artisan ts:publish` command to transform the changed PHP files into TypeScript files.
113
+
114
+ ### Command Execution Notes
115
+
116
+ The plugin runs the configured `command` with Node's `child_process.exec()` from the Vite project root.
117
+
118
+ This has two important consequences:
119
+
120
+ 1. The command runs in a non-interactive shell.
121
+ 2. Shell aliases such as `sail` are usually not available.
122
+
123
+ If you are using Laravel Sail and Vite is running on your host machine, prefer `./vendor/bin/sail artisan ts:publish` instead of `sail artisan ts:publish`.
124
+
125
+ If Vite is already running inside the PHP container, use `php artisan ts:publish`.
126
+
127
+ When the publish command rewrites the collected-files manifest, the plugin only reloads the watched file list. It does not run the publish command again for that manifest update, which prevents command loops.
128
+
129
+ ### Usage
130
+
131
+ To use the Vite plugin, you need to add it to your Vite configuration file. Below is an example of how to add the plugin to your Vite configuration file:
132
+
133
+ ```javascript
134
+ import { defineConfig } from "vite";
135
+ import { laravelTsPublish } from "@tolki/ts/vite";
136
+
137
+ export default defineConfig({
138
+ plugins: [laravelTsPublish()],
139
+ });
140
+ ```
141
+
142
+ #### Laravel Sail
143
+
144
+ Choose the command based on where `vite dev` is running:
145
+
146
+ - Vite running on the host machine: `./vendor/bin/sail artisan ts:publish`
147
+ - Vite running inside the container: `php artisan ts:publish`
148
+
149
+ Using just `sail artisan ts:publish` often fails because `sail` is commonly defined as a shell alias and aliases are not resolved by `exec()`.
150
+
151
+ ### Default Functionality
152
+
153
+ By default, the plugin will work in the following way:
154
+
155
+ 1. It will call `php artisan ts:publish` as the republish command when a file changes.
156
+ 2. It will look for the list of transformed PHP files here: `resources/js/types/data/laravel-ts-collected-files.json`.
157
+ 3. If that manifest file changes, it will reload the watched file list without calling the publish command again.
158
+ 4. It will reload the page after a successful publish triggered by a watched PHP file change.
159
+ 5. It will call the publish command on `vite build` before bundling, with `--only-functional` appended by default (since TypeScript interfaces are type-only and erased at compile time).
160
+ 6. It will throw an error if the publish command fails on `vite build`.
161
+ 7. When a single PHP file changes during `vite dev`, it will use `--source` to republish only that file instead of running a full publish.
162
+ 8. It will append `--quiet` to every command by default, suppressing all console output since the plugin only needs the exit code.
163
+
164
+ #### Single-File Republishing
165
+
166
+ The JSON file list manifest uses the `filepath[]` array format (produced by `laravel-ts-publish`), the plugin will automatically use the `--source` flag to republish only the changed file during development:
167
+
168
+ ```bash
169
+ # Instead of running the full command:
170
+ php artisan ts:publish
171
+
172
+ # The plugin runs a targeted command:
173
+ php artisan ts:publish --source="app/Enums/Status.php"
174
+ ```
175
+
176
+ This can reduce per-change latency from seconds to near-instant on large projects with hundreds of files.
177
+
178
+ The plugin derives the source command automatically from the `command` option by appending `--source="{file}"`. You can customize this with the `sourceCommand` option or disable it entirely by setting `sourceCommand: false`.
179
+
180
+ Full startup commands (`runOnDevStart`, `runOnBuildStart`) always use the full `command` to ensure all files are generated.
181
+
182
+ #### Manifest Updates
183
+
184
+ The collected-files manifest is treated as configuration input for the watcher, not as a publish trigger.
185
+
186
+ That means when `ts:publish` updates `resources/js/types/data/laravel-ts-collected-files.json`, the plugin will refresh its internal watched-file list and continue. It will not immediately run `ts:publish` again from that manifest write.
187
+
188
+ ### Plugin Options
189
+
190
+ The plugin accepts an options object to customize its behavior. It is recommended to use `.env` config settings to sync settings between the PHP side and the Vite plugin for the `filename` and `directory` options.
191
+
192
+ Below are the available options with a description and default values:
193
+
194
+ ```javascript
195
+ import { defineConfig } from "vite";
196
+ import { laravelTsPublish } from "@tolki/ts/vite";
197
+
198
+ export default defineConfig({
199
+ plugins: [
200
+ laravelTsPublish({
201
+ /**
202
+ * The publish command to run when a watched PHP file changes.
203
+ *
204
+ * This command runs through Node's `exec()` from the Vite project root.
205
+ * Shell aliases like `sail` are usually not available here.
206
+ *
207
+ * If Vite runs on the host machine and your app uses Sail, prefer
208
+ * `./vendor/bin/sail artisan ts:publish`.
209
+ *
210
+ * If Vite already runs inside the PHP container, use
211
+ * `php artisan ts:publish`.
212
+ */
213
+ command: "php artisan ts:publish",
214
+ /**
215
+ * The filename of the JSON manifest listing collected PHP files.
216
+ */
217
+ filename: "laravel-ts-collected-files.json",
218
+ /**
219
+ * The directory where the JSON manifest file exists, relative to the Vite root.
220
+ */
221
+ directory: "resources/js/types/data/",
222
+ /**
223
+ * Whether to run the publish command once when `vite dev` starts.
224
+ *
225
+ * Has no effect during `vite build`.
226
+ */
227
+ runOnDevStart: false,
228
+ /**
229
+ * Whether to run the publish command once before bundling during `vite build`.
230
+ *
231
+ * Has no effect during `vite dev`.
232
+ */
233
+ runOnBuildStart: true,
234
+ /**
235
+ * Whether to trigger a full browser reload after the
236
+ * command runs successfully during `vite dev`.
237
+ *
238
+ * Has no effect during `vite build`.
239
+ */
240
+ reload: true,
241
+ /**
242
+ * Whether to throw an error (aborting the build) when the command fails.
243
+ *
244
+ * When not specified, defaults to `true` during `vite build`
245
+ * and `false` during `vite dev`.
246
+ *
247
+ * When specified, it will apply to both `vite dev` and `vite build`.
248
+ */
249
+ failOnError: undefined,
250
+ /**
251
+ * The command template for single-file republishing during `vite dev`.
252
+ *
253
+ * When a watched PHP file changes, this command is used instead of the
254
+ * full `command`. The `{file}` placeholder is replaced with the relative
255
+ * file path from the manifest for the changed file (exactly as it
256
+ * appears in the manifest array).
257
+ *
258
+ * When not specified, it is auto-derived by appending
259
+ * ` --source="{file}"` to the `command` option.
260
+ *
261
+ * Set to `false` to always run the full command.
262
+ */
263
+ sourceCommand: 'php artisan ts:publish --source="{file}"',
264
+ /**
265
+ * Whether to append `--only-functional` to the command during `vite build`.
266
+ *
267
+ * TypeScript interfaces are type-only and erased at compile time, so
268
+ * generating them during production builds is unnecessary.
269
+ *
270
+ * Has no effect during `vite dev`.
271
+ */
272
+ onBuildOnlyFunctional: true,
273
+ /**
274
+ * Whether to append `--quiet` to every artisan command the plugin runs.
275
+ *
276
+ * The plugin only needs the exit code to determine success or failure;
277
+ * all stdout is ignored. Passing `--quiet` suppresses console output
278
+ * and Laravel Prompts rendering, which speeds up execution.
279
+ */
280
+ quiet: true,
281
+ }),
282
+ ],
283
+ });
284
+ ```
285
+
286
+ #### Example for a Host-Machine Vite Dev Server with Sail
287
+
288
+ ```javascript
289
+ import { defineConfig } from "vite";
290
+ import { laravelTsPublish } from "@tolki/ts/vite";
291
+
292
+ export default defineConfig({
293
+ plugins: [
294
+ laravelTsPublish({
295
+ command: "./vendor/bin/sail artisan ts:publish",
296
+ }),
297
+ ],
298
+ });
299
+ ```
300
+
301
+ #### Example for Vite Running Inside the Container
302
+
303
+ ```javascript
304
+ import { defineConfig } from "vite";
305
+ import { laravelTsPublish } from "@tolki/ts/vite";
306
+
307
+ export default defineConfig({
308
+ plugins: [
309
+ laravelTsPublish({
310
+ command: "php artisan ts:publish",
311
+ }),
312
+ ],
313
+ });
314
+ ```
315
+
316
+ <!-- AUTO-GENERATED-DOCS:END -->
@@ -0,0 +1,59 @@
1
+ import { AsEnum, CaseValue, DefineEnumResult, EnumConst, FromResult } from '../packages/types/src/index.ts';
2
+ export type { AsEnum, CaseValue, DefineEnumResult, EnumConst, FromResult };
3
+ /**
4
+ * Creates an enum instance from a case value similar to PHP's `BackedEnum::from()`
5
+ *
6
+ * It will remove all the cases and make the matching case's value available as `value`
7
+ *
8
+ * All instance methods will be flattened from an object of case keys & values to a key/value pair for the matched case.
9
+ *
10
+ * The enumObj is the published enum from the Laravel TypeScript Publish package.
11
+ *
12
+ * @see https://github.com/abetwothree/laravel-ts-publish#enum-metadata--tolki-enum-package
13
+ * @see https://tolki.abe.dev/enums/enum-utilities-list.html#from
14
+ *
15
+ * @param enumObj - The enum const object to resolve from.
16
+ * @param value - The case value to resolve. Must be one of the values defined in the enum const's cases.
17
+ * @returns The resolved enum case with its associated methods and properties for the value provided.
18
+ * @throws If the value does not match any case in the enum, an error is thrown.
19
+ */
20
+ export declare function from<TEnum extends EnumConst, const TValue extends CaseValue<TEnum>>(enumObj: TEnum, value: TValue): FromResult<TEnum, TValue>;
21
+ /**
22
+ * Similar to the {@linkcode from | from} function but returns null instead of throwing an error for invalid values.
23
+ *
24
+ * Mirrors PHP's `BackedEnum::tryFrom()`.
25
+ *
26
+ * @see https://tolki.abe.dev/enums/enum-utilities-list.html#tryfrom
27
+ *
28
+ * @param enumObj - The enum const object to resolve from.
29
+ * @param value - The case value to resolve.
30
+ * @returns The resolved enum case, or null if the value does not match any case.
31
+ */
32
+ export declare function tryFrom<TEnum extends EnumConst, const TValue extends CaseValue<TEnum>>(enumObj: TEnum, value: TValue): FromResult<TEnum, TValue> | null;
33
+ /**
34
+ * Returns all enum cases as resolved instances by running each case value through the {@linkcode from | from} function.
35
+ *
36
+ * Mirrors PHP's `BackedEnum::cases()`, returning one resolved instance per case defined in the enum const.
37
+ *
38
+ * @see https://tolki.abe.dev/enums/enum-utilities-list.html#cases
39
+ *
40
+ * @param enumObj - The enum const object to resolve all cases from.
41
+ * @returns An array of resolved enum instances, one for each case.
42
+ */
43
+ export declare function cases<TEnum extends EnumConst>(enumObj: TEnum): Array<FromResult<TEnum, CaseValue<TEnum>>>;
44
+ /**
45
+ * Factory function that creates an enriched enum object
46
+ *
47
+ * It automatically binds Tolki helper methods {@linkcode from | from}, {@linkcode tryFrom | tryFrom}, and {@linkcode cases | cases}.
48
+ *
49
+ * This allows your published enum to have PHP-like enum behavior with type safety and autocompletion in TypeScript.
50
+ *
51
+ * The original enum data is preserved and the PHP like enum methods are attached directly to the returned object.
52
+ *
53
+ * @see https://tolki.abe.dev/enums/enum-utilities-list.html#defineenum
54
+ *
55
+ * @param enumObj - The raw enum const object to enrich.
56
+ * @returns The enum object with `from`, `tryFrom`, and `cases` methods bound to it.
57
+ */
58
+ export declare function defineEnum<const TEnum extends EnumConst>(enumObj: TEnum): DefineEnumResult<TEnum>;
59
+ //# sourceMappingURL=enums.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"enums.d.ts","sourceRoot":"","sources":["../src/enums.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACR,MAAM,EACN,SAAS,EACT,gBAAgB,EAChB,SAAS,EACT,UAAU,EACb,MAAM,cAAc,CAAC;AAGtB,YAAY,EAAE,MAAM,EAAE,SAAS,EAAE,gBAAgB,EAAE,SAAS,EAAE,UAAU,EAAE,CAAC;AAE3E;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,IAAI,CAChB,KAAK,SAAS,SAAS,EACvB,KAAK,CAAC,MAAM,SAAS,SAAS,CAAC,KAAK,CAAC,EACvC,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,GAAG,UAAU,CAAC,KAAK,EAAE,MAAM,CAAC,CA8C1D;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,OAAO,CACnB,KAAK,SAAS,SAAS,EACvB,KAAK,CAAC,MAAM,SAAS,SAAS,CAAC,KAAK,CAAC,EACvC,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,GAAG,UAAU,CAAC,KAAK,EAAE,MAAM,CAAC,GAAG,IAAI,CAMjE;AAED;;;;;;;;;GASG;AACH,wBAAgB,KAAK,CAAC,KAAK,SAAS,SAAS,EACzC,OAAO,EAAE,KAAK,GACf,KAAK,CAAC,UAAU,CAAC,KAAK,EAAE,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,CAI5C;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAgB,UAAU,CAAC,KAAK,CAAC,KAAK,SAAS,SAAS,EACpD,OAAO,EAAE,KAAK,GACf,gBAAgB,CAAC,KAAK,CAAC,CA2BzB"}
package/dist/enums.js ADDED
@@ -0,0 +1,60 @@
1
+ import { isArray as y } from "@tolki/utils";
2
+ function a(e, s) {
3
+ const n = new Set(e._cases ?? []);
4
+ let r;
5
+ for (const t of n)
6
+ if (e[t] === s) {
7
+ r = t;
8
+ break;
9
+ }
10
+ if (!r) {
11
+ const t = Array.from(n).map((c) => e[c]);
12
+ throw new Error(
13
+ `Value "${String(s)}" does not match any case in the enum. Values: ${t.join(", ")}, Cases: ${[...n].join(", ")}`
14
+ );
15
+ }
16
+ const o = { value: s }, f = new Set(e._methods ?? []), i = e._helpers, h = new Set(
17
+ y(i) ? i : []
18
+ ), l = /* @__PURE__ */ new Set([
19
+ "_cases",
20
+ "_methods",
21
+ "_helpers",
22
+ "_static"
23
+ ]);
24
+ for (const [t, c] of Object.entries(e))
25
+ l.has(t) || n.has(t) || h.has(t) || (f.has(t) ? o[t] = c[r] : o[t] = c);
26
+ return o.name = r, o;
27
+ }
28
+ function p(e, s) {
29
+ try {
30
+ return a(e, s);
31
+ } catch {
32
+ return null;
33
+ }
34
+ }
35
+ function u(e) {
36
+ return (e._cases ?? []).map(
37
+ (s) => a(e, e[s])
38
+ );
39
+ }
40
+ function m(e) {
41
+ const s = {
42
+ from: (r) => a(e, r),
43
+ tryFrom: (r) => p(e, r),
44
+ cases: () => u(e)
45
+ }, n = Object.keys(s);
46
+ return Object.assign(
47
+ /* @__PURE__ */ Object.create(null),
48
+ e,
49
+ s,
50
+ {
51
+ _helpers: n
52
+ }
53
+ );
54
+ }
55
+ export {
56
+ u as cases,
57
+ m as defineEnum,
58
+ a as from,
59
+ p as tryFrom
60
+ };
@@ -0,0 +1,3 @@
1
+ export * from './enums';
2
+ export * from './routes';
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,SAAS,CAAC;AACxB,cAAc,UAAU,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,14 @@
1
+ import { cases as o, defineEnum as f, from as u, tryFrom as r } from "./enums.js";
2
+ import { addRouteDefault as a, defineRoute as m, formSafeOptions as R, getRouteDefaults as d, resetRouteDefaults as l, setRouteDefaults as n } from "./routes.js";
3
+ export {
4
+ a as addRouteDefault,
5
+ o as cases,
6
+ f as defineEnum,
7
+ m as defineRoute,
8
+ R as formSafeOptions,
9
+ u as from,
10
+ d as getRouteDefaults,
11
+ l as resetRouteDefaults,
12
+ n as setRouteDefaults,
13
+ r as tryFrom
14
+ };
@@ -0,0 +1,67 @@
1
+ import { DefineRouteResult, RouteArgMeta, RouteCallResult, RouteCallResultWithComponent, RouteComponentType, RouteFormResult, RouteMetadata, RouteQueryOptions } from '../packages/types/src/index.ts';
2
+ export type { DefineRouteResult, RouteArgMeta, RouteCallResult, RouteCallResultWithComponent, RouteComponentType, RouteFormResult, RouteMetadata, RouteQueryOptions, };
3
+ /**
4
+ * Set global default route parameter values.
5
+ *
6
+ * These values are substituted into URL segments automatically when
7
+ * the caller doesn't provide them. Mirrors Laravel's `URL::defaults()`.
8
+ * Accepts a static object or a factory function for lazy evaluation.
9
+ *
10
+ * @param defaults - A record of parameter names to default values, or a factory function.
11
+ */
12
+ export declare function setRouteDefaults(defaults: Record<string, string | number | boolean> | (() => Record<string, string | number | boolean>)): void;
13
+ /**
14
+ * Add or update a single route default.
15
+ *
16
+ * If a default already exists for the given parameter name, it is overwritten.
17
+ *
18
+ * @param key - The parameter name.
19
+ * @param value - The default value.
20
+ */
21
+ export declare function addRouteDefault(key: string, value: string | number | boolean): void;
22
+ /**
23
+ * Get the current route defaults (evaluates the thunk).
24
+ *
25
+ * @returns The current route defaults record.
26
+ */
27
+ export declare function getRouteDefaults(): Record<string, string | number | boolean>;
28
+ /**
29
+ * Reset route defaults to an empty object (useful for testing).
30
+ */
31
+ export declare function resetRouteDefaults(): void;
32
+ /**
33
+ * Injects `_method` into query options for HTML form method spoofing.
34
+ *
35
+ * HTML forms only support GET and POST. For PUT, PATCH, DELETE, and HEAD,
36
+ * Laravel uses a hidden `_method` field sent via POST (or GET for HEAD).
37
+ *
38
+ * @param method - The intended HTTP method.
39
+ * @param options - Optional query options to merge with.
40
+ * @returns RouteQueryOptions with `_method` injected.
41
+ */
42
+ export declare function formSafeOptions(method: string, options?: RouteQueryOptions): RouteQueryOptions;
43
+ /**
44
+ * Define a Laravel route in TypeScript using compact metadata.
45
+ *
46
+ * Returns a callable object with:
47
+ * - Direct invocation returning `{ url, method }` with `toString()`
48
+ * - `.url(...)` returning just the URL string
49
+ * - `.definition` — the raw metadata passthrough
50
+ * - Per-verb methods (`.get(...)`, `.post(...)`, etc.)
51
+ * - `.form(...)` — form submission helper with `{ action, method }`
52
+ * - `.form.<verb>(...)` — per-verb form methods with method spoofing
53
+ * - `toString()` returning the URL with no params
54
+ *
55
+ * Supports 6 calling conventions:
56
+ * 1. Named object: `fn({ post: 42 })`
57
+ * 2. Spread scalars: `fn(42)` or `fn(2, 42)`
58
+ * 3. Array form: `fn([42])` or `fn([2, 42])`
59
+ * 4. Positional → named mapping
60
+ * 5. Naked model shortcut: `fn({ id: 42 })`
61
+ * 6. Trailing query options: `fn(42, { _query: { page: 2 } })`
62
+ *
63
+ * @param metadata - The route metadata object with url, methods, and optional args.
64
+ * @returns A defineRoute result — callable with per-verb methods, .url(), .form, and .definition.
65
+ */
66
+ export declare function defineRoute<const TMethods extends readonly string[], const TArgs extends readonly RouteArgMeta[] = readonly [], const TComponent extends RouteComponentType | undefined = undefined>(metadata: RouteMetadata<TMethods, TArgs, TComponent>): DefineRouteResult<TMethods, TArgs, TComponent>;
67
+ //# sourceMappingURL=routes.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"routes.d.ts","sourceRoot":"","sources":["../src/routes.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACR,iBAAiB,EACjB,YAAY,EACZ,eAAe,EACf,4BAA4B,EAC5B,kBAAkB,EAClB,eAAe,EACf,aAAa,EACb,iBAAiB,EACpB,MAAM,cAAc,CAAC;AAYtB,YAAY,EACR,iBAAiB,EACjB,YAAY,EACZ,eAAe,EACf,4BAA4B,EAC5B,kBAAkB,EAClB,eAAe,EACf,aAAa,EACb,iBAAiB,GACpB,CAAC;AAiBF;;;;;;;;GAQG;AACH,wBAAgB,gBAAgB,CAC5B,QAAQ,EACF,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,OAAO,CAAC,GACzC,CAAC,MAAM,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,OAAO,CAAC,CAAC,GACxD,IAAI,CAEN;AAED;;;;;;;GAOG;AACH,wBAAgB,eAAe,CAC3B,GAAG,EAAE,MAAM,EACX,KAAK,EAAE,MAAM,GAAG,MAAM,GAAG,OAAO,GACjC,IAAI,CAMN;AAED;;;;GAIG;AACH,wBAAgB,gBAAgB,IAAI,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,OAAO,CAAC,CAE5E;AAED;;GAEG;AACH,wBAAgB,kBAAkB,IAAI,IAAI,CAEzC;AA8YD;;;;;;;;;GASG;AACH,wBAAgB,eAAe,CAC3B,MAAM,EAAE,MAAM,EACd,OAAO,CAAC,EAAE,iBAAiB,GAC5B,iBAAiB,CAWnB;AAED;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,wBAAgB,WAAW,CACvB,KAAK,CAAC,QAAQ,SAAS,SAAS,MAAM,EAAE,EACxC,KAAK,CAAC,KAAK,SAAS,SAAS,YAAY,EAAE,GAAG,SAAS,EAAE,EACzD,KAAK,CAAC,UAAU,SAAS,kBAAkB,GAAG,SAAS,GAAG,SAAS,EAEnE,QAAQ,EAAE,aAAa,CAAC,QAAQ,EAAE,KAAK,EAAE,UAAU,CAAC,GACrD,iBAAiB,CAAC,QAAQ,EAAE,KAAK,EAAE,UAAU,CAAC,CAyFhD"}
package/dist/routes.js ADDED
@@ -0,0 +1,261 @@
1
+ import { isString as U, isFunction as E, isUndefined as j, isNull as R, isObject as g, isArray as w, isNumber as K, isBoolean as Q } from "@tolki/utils";
2
+ const C = () => ({});
3
+ let b = C;
4
+ function I(e) {
5
+ b = E(e) ? e : () => ({ ...e });
6
+ }
7
+ function N(e, n) {
8
+ const o = b;
9
+ b = () => ({
10
+ ...o(),
11
+ [e]: n
12
+ });
13
+ }
14
+ function T() {
15
+ return { ...b() };
16
+ }
17
+ function V() {
18
+ b = C;
19
+ }
20
+ function O(e, n) {
21
+ if (j(e) || R(e))
22
+ return "";
23
+ if (g(e)) {
24
+ if (n?._routeKey) {
25
+ const o = n._routeKey;
26
+ if (o in e)
27
+ return String(e[o]);
28
+ if ("id" in e)
29
+ return String(e.id);
30
+ throw new Error(
31
+ `Route error: object passed as '${n.name}' parameter is missing route model binding key '${o}'.`
32
+ );
33
+ }
34
+ if (n?._enumValues) {
35
+ if ("value" in e)
36
+ return String(e.value);
37
+ throw new Error(
38
+ `Route error: object passed as '${n.name}' parameter is missing enum '.value' property.`
39
+ );
40
+ }
41
+ return "id" in e ? String(e.id) : String(e);
42
+ }
43
+ return String(e);
44
+ }
45
+ function S(e, n) {
46
+ if (R(n) || j(n))
47
+ return [];
48
+ if (Q(n))
49
+ return [`${encodeURIComponent(e)}=${n ? "1" : "0"}`];
50
+ if (w(n)) {
51
+ const o = [];
52
+ for (let r = 0; r < n.length; r++)
53
+ o.push(
54
+ ...S(`${e}[${r}]`, n[r])
55
+ );
56
+ return o;
57
+ }
58
+ if (g(n)) {
59
+ const o = [];
60
+ for (const [r, h] of Object.entries(n))
61
+ o.push(
62
+ ...S(`${e}[${r}]`, h)
63
+ );
64
+ return o;
65
+ }
66
+ return [`${encodeURIComponent(e)}=${encodeURIComponent(String(n))}`];
67
+ }
68
+ function x(e) {
69
+ const n = [];
70
+ for (const [o, r] of Object.entries(e))
71
+ n.push(...S(o, r));
72
+ return n.length === 0 ? "" : `?${n.join("&")}`;
73
+ }
74
+ function $(e, n) {
75
+ if (e.length === 0)
76
+ return [{}, void 0];
77
+ const o = n;
78
+ let r;
79
+ if (o.length === 0)
80
+ return e.length === 1 && g(e[0]) ? [{}, e[0]] : [{}, void 0];
81
+ const h = new Set(o.map((s) => s.name));
82
+ if (e.length >= 2) {
83
+ const s = e[e.length - 1];
84
+ g(s) && !Object.keys(s).some(
85
+ (t) => h.has(t)
86
+ ) && e.length > o.length && (r = s, e = e.slice(0, -1));
87
+ }
88
+ if (e.length === 1 && w(e[0])) {
89
+ const s = e[0], m = {};
90
+ for (let t = 0; t < s.length && t < o.length; t++)
91
+ m[o[t].name] = s[t];
92
+ return [m, r];
93
+ }
94
+ if (e.length === 1 && g(e[0])) {
95
+ const s = e[0];
96
+ if (Object.keys(s).some((t) => h.has(t))) {
97
+ const t = {}, u = {};
98
+ for (const [c, l] of Object.entries(s))
99
+ h.has(c) ? t[c] = l : c === "_query" ? r = {
100
+ ...r,
101
+ _query: l
102
+ } : u[c] = l;
103
+ return Object.keys(u).length > 0 && (r = { ...r, ...u }), [
104
+ t,
105
+ Object.keys(r ?? {}).length > 0 ? r : void 0
106
+ ];
107
+ }
108
+ if (o.length === 1) {
109
+ const t = o[0], u = t.name, c = t._routeKey;
110
+ if (c && c in s || "id" in s || "_routeKey" in s)
111
+ return [{ [u]: s }, r];
112
+ }
113
+ return [{}, { ...r, ...s }];
114
+ }
115
+ if (e.length >= 1 && e.every((s) => U(s) || K(s) || g(s))) {
116
+ const s = {};
117
+ for (let m = 0; m < e.length && m < o.length; m++)
118
+ s[o[m].name] = e[m];
119
+ return [s, r];
120
+ }
121
+ return [{}, r];
122
+ }
123
+ function d(e, n, o, r) {
124
+ let h = e;
125
+ !h.startsWith("/") && !h.startsWith("//") && !h.includes("://") && (h = `//${h}`);
126
+ const s = new Map(o.map((i) => [i.name, i])), m = b(), t = {};
127
+ for (const i of o)
128
+ i.name in m && !(i.name in n) && (t[i.name] = m[i.name]);
129
+ for (const [i, f] of Object.entries(n))
130
+ t[i] = f;
131
+ for (const i of o)
132
+ if (i.where && i.name in t) {
133
+ const f = O(t[i.name], i);
134
+ if (f !== "") {
135
+ let p;
136
+ try {
137
+ p = new RegExp(`^${i.where}$`);
138
+ } catch {
139
+ throw new Error(
140
+ `Route error: '${i.name}' has invalid 'where' constraint pattern '${i.where}'.`
141
+ );
142
+ }
143
+ if (!p.test(f))
144
+ throw new Error(
145
+ `Route error: '${i.name}' parameter '${f}' does not match required format '${i.where}'.`
146
+ );
147
+ }
148
+ }
149
+ const c = h.replace(
150
+ /{([^{}?]+)(\??)}/g,
151
+ (i, f, p) => {
152
+ const y = t[f], q = s.get(f);
153
+ if (!p && (j(y) || R(y)))
154
+ throw new Error(
155
+ `Route error: '${f}' parameter is required.`
156
+ );
157
+ const D = O(y, q);
158
+ return encodeURI(D).replace(/%7C/g, "|").replace(/%25/g, "%").replace(/\$/g, "%24");
159
+ }
160
+ ).replace(/([^:])\/{2,}/g, "$1/").replace(/\/+$/, "") || "/", l = {};
161
+ if (r) {
162
+ if (r.mergeQuery) {
163
+ const i = j(globalThis.window) ? new URLSearchParams() : new URLSearchParams(globalThis.window.location.search);
164
+ for (const [f, p] of i.entries())
165
+ l[f] = p;
166
+ for (const [f, p] of Object.entries(r.mergeQuery))
167
+ R(p) || j(p) ? delete l[f] : l[f] = p;
168
+ }
169
+ for (const [i, f] of Object.entries(r))
170
+ if (i === "_query" && g(f))
171
+ for (const [p, y] of Object.entries(
172
+ f
173
+ ))
174
+ l[p] = y;
175
+ else i !== "_query" && i !== "mergeQuery" && (l[i] = f);
176
+ }
177
+ const a = x(l);
178
+ return c + a;
179
+ }
180
+ function k(e, n) {
181
+ return {
182
+ url: e,
183
+ method: n,
184
+ toString() {
185
+ return e;
186
+ }
187
+ };
188
+ }
189
+ function _(e, n) {
190
+ return {
191
+ action: e,
192
+ method: n === "get" || n === "head" ? "get" : "post",
193
+ toString() {
194
+ return e;
195
+ }
196
+ };
197
+ }
198
+ function P(e, n) {
199
+ const o = n?.mergeQuery ? "mergeQuery" : "_query", r = n?.[o] ?? {};
200
+ return {
201
+ ...n,
202
+ [o]: {
203
+ ...r,
204
+ _method: e.toUpperCase()
205
+ }
206
+ };
207
+ }
208
+ function v(e) {
209
+ const n = e.args ?? [], o = e.methods[0] ?? "get", r = (...t) => {
210
+ const [u, c] = $(t, n), l = d(e.url, u, n, c);
211
+ return k(l, o);
212
+ }, s = Object.assign(r, {
213
+ url: (...t) => {
214
+ const [u, c] = $(t, n);
215
+ return d(e.url, u, n, c);
216
+ },
217
+ definition: e,
218
+ toString() {
219
+ return d(e.url, {}, n);
220
+ }
221
+ });
222
+ for (const t of e.methods)
223
+ Object.assign(s, {
224
+ [t]: (...u) => {
225
+ const [c, l] = $(u, n), a = d(e.url, c, n, l);
226
+ return k(a, t);
227
+ }
228
+ });
229
+ const m = (...t) => {
230
+ const [u, c] = $(t, n), l = d(e.url, u, n, c);
231
+ return _(l, o);
232
+ };
233
+ for (const t of e.methods) {
234
+ const u = t !== "get" && t !== "post";
235
+ Object.assign(m, {
236
+ [t]: (...c) => {
237
+ const [l, a] = $(c, n), i = u ? P(t, a) : a, f = d(e.url, l, n, i);
238
+ return _(f, t);
239
+ }
240
+ });
241
+ }
242
+ if (Object.assign(s, { form: m }), e.component !== void 0)
243
+ if (Object.assign(s, { component: e.component }), U(e.component)) {
244
+ const t = e.component;
245
+ Object.assign(s, {
246
+ withComponent: (...u) => ({ ...r(...u), component: t })
247
+ });
248
+ } else
249
+ Object.assign(s, {
250
+ withComponent: (t, ...u) => ({ ...r(...u), component: t })
251
+ });
252
+ return s;
253
+ }
254
+ export {
255
+ N as addRouteDefault,
256
+ v as defineRoute,
257
+ P as formSafeOptions,
258
+ T as getRouteDefaults,
259
+ V as resetRouteDefaults,
260
+ I as setRouteDefaults
261
+ };
@@ -0,0 +1,170 @@
1
+ import { Plugin } from 'vite';
2
+ /**
3
+ * Escape a value for safe interpolation into a shell command string.
4
+ *
5
+ * Uses POSIX single-quote wrapping: the only character that requires
6
+ * escaping inside single quotes is the single quote itself.
7
+ *
8
+ * @param value - The raw string to escape.
9
+ * @returns A shell-safe string.
10
+ */
11
+ export declare function escapeShellArg(value: string): string;
12
+ export interface LaravelTsPublishOptions {
13
+ /**
14
+ * The command to run when a watched PHP file changes.
15
+ *
16
+ * The command is executed with Node's `exec()` using the Vite project root
17
+ * as the current working directory. Because it runs in a non-interactive
18
+ * shell, shell aliases such as `sail` are usually not available.
19
+ *
20
+ * Common setups:
21
+ * - Run Vite on the host machine with Laravel Sail: `./vendor/bin/sail artisan ts:publish`
22
+ * - Run Vite inside the container: `php artisan ts:publish`
23
+ *
24
+ * @default "php artisan ts:publish"
25
+ */
26
+ command?: string;
27
+ /**
28
+ * The filename of the JSON manifest listing collected PHP files.
29
+ *
30
+ * @default "laravel-ts-collected-files.json"
31
+ */
32
+ filename?: string;
33
+ /**
34
+ * The directory where the JSON manifest file exists, relative to the Vite root.
35
+ *
36
+ * @default "resources/js/types/data/"
37
+ */
38
+ directory?: string;
39
+ /**
40
+ * Whether to run the publish command once when `vite dev` starts.
41
+ *
42
+ * Has no effect during `vite build`.
43
+ *
44
+ * @default false
45
+ */
46
+ runOnDevStart?: boolean;
47
+ /**
48
+ * Whether to run the publish command once before bundling during
49
+ * `vite build`.
50
+ *
51
+ * Has no effect during `vite dev`.
52
+ *
53
+ * @default true
54
+ */
55
+ runOnBuildStart?: boolean;
56
+ /**
57
+ * Whether to trigger a full browser reload after the command runs
58
+ * successfully during `vite dev`.
59
+ *
60
+ * Has no effect during `vite build`.
61
+ *
62
+ * @default true
63
+ */
64
+ reload?: boolean;
65
+ /**
66
+ * Whether to throw an error (aborting the build) when the command fails.
67
+ *
68
+ * When not specified, defaults to `true` during `vite build` and `false`
69
+ * during `vite dev`.
70
+ */
71
+ failOnError?: boolean;
72
+ /**
73
+ * The command template for single-file republishing during `vite dev`.
74
+ *
75
+ * When a watched PHP file changes, this command is used instead of the
76
+ * full `command` to republish only the changed file. The `{file}`
77
+ * placeholder is replaced with the shell-escaped relative file path
78
+ * from the manifest — do not wrap it in additional quotes.
79
+ *
80
+ * When not specified, it is auto-derived by appending
81
+ * ` --source={file}` to the `command` option.
82
+ *
83
+ * Set to `false` to disable single-file republishing and always run
84
+ * the full command.
85
+ *
86
+ * @default Derived from the `command` option: 'php artisan ts:publish --source={file}'
87
+ */
88
+ sourceCommand?: string | false;
89
+ /**
90
+ * Whether to append `--only-functional` to the command during `vite build`.
91
+ *
92
+ * Model interfaces are type-only and erased at compile time, so generating
93
+ * them during production builds is unnecessary. When `true`, the build
94
+ * command becomes e.g. `php artisan ts:publish --only-functional`.
95
+ *
96
+ * Has no effect during `vite dev`.
97
+ *
98
+ * @default true
99
+ */
100
+ onBuildOnlyFunctional?: boolean;
101
+ /**
102
+ * Whether to append `--quiet` to every artisan command the plugin runs.
103
+ *
104
+ * The plugin only needs the exit code to determine success or failure;
105
+ * all stdout is ignored. Passing `--quiet` suppresses console output
106
+ * and Laravel Prompts rendering, which speeds up execution.
107
+ *
108
+ * @default true
109
+ */
110
+ quiet?: boolean;
111
+ }
112
+ /**
113
+ * Vite plugin that watches PHP source files listed in the Laravel TypeScript
114
+ * Publisher manifest and re-runs the publish command when any of them change.
115
+ *
116
+ * - **Build mode** (`vite build`): runs the command once before bundling so
117
+ * TypeScript definitions are always up-to-date (disable with
118
+ * `runOnBuildStart: false`). Fails the build by default if the command errors.
119
+ * - **Dev mode** (`vite dev`): loads the manifest, explicitly adds the listed
120
+ * PHP files to the dev-server file watcher, and re-runs the command when any
121
+ * of them change via HMR. Optionally runs the command once at startup when
122
+ * `runOnDevStart` is `true`. Sends a full browser reload after every
123
+ * successful run (disable with `reload: false`). Manifest updates only
124
+ * refresh the watched-file list and do not trigger the command again.
125
+ * - **Command execution**: the configured command runs through Node's
126
+ * `child_process.exec()` from the Vite project root. Shell aliases are not
127
+ * resolved, so use a real executable path such as `./vendor/bin/sail` when
128
+ * running Vite on the host with Laravel Sail.
129
+ *
130
+ * @param options - Configuration options for the plugin.
131
+ * @returns A Vite plugin object.
132
+ *
133
+ * @example
134
+ * ```ts
135
+ * // vite.config.ts
136
+ * import { defineConfig } from "vite";
137
+ * import { laravelTsPublish } from "@tolki/ts/vite";
138
+ *
139
+ * export default defineConfig({
140
+ * plugins: [
141
+ * laravelTsPublish(),
142
+ * ],
143
+ * });
144
+ * ```
145
+ *
146
+ * @example
147
+ * ```ts
148
+ * // With Laravel Sail
149
+ * laravelTsPublish({
150
+ * command: "./vendor/bin/sail artisan ts:publish",
151
+ * });
152
+ * ```
153
+ * @example
154
+ * ```ts
155
+ * // When Vite is already running inside the PHP container
156
+ * laravelTsPublish({
157
+ * command: "php artisan ts:publish",
158
+ * });
159
+ * ```
160
+ *
161
+ * @example
162
+ * ```ts
163
+ * // Also run the command when the dev server starts
164
+ * laravelTsPublish({
165
+ * runOnDevStart: true,
166
+ * });
167
+ * ```
168
+ */
169
+ export declare function laravelTsPublish(options?: LaravelTsPublishOptions): Plugin;
170
+ //# sourceMappingURL=vite-plugin.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vite-plugin.d.ts","sourceRoot":"","sources":["../src/vite-plugin.ts"],"names":[],"mappings":"AAKA,OAAO,EAEH,KAAK,MAAM,EAGd,MAAM,MAAM,CAAC;AAId;;;;;;;;GAQG;AACH,wBAAgB,cAAc,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAUpD;AAED,MAAM,WAAW,uBAAuB;IACpC;;;;;;;;;;;;OAYG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB;;;;OAIG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB;;;;OAIG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB;;;;;;OAMG;IACH,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB;;;;;;;OAOG;IACH,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B;;;;;;;OAOG;IACH,MAAM,CAAC,EAAE,OAAO,CAAC;IACjB;;;;;OAKG;IACH,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB;;;;;;;;;;;;;;;OAeG;IACH,aAAa,CAAC,EAAE,MAAM,GAAG,KAAK,CAAC;IAC/B;;;;;;;;;;OAUG;IACH,qBAAqB,CAAC,EAAE,OAAO,CAAC;IAChC;;;;;;;;OAQG;IACH,KAAK,CAAC,EAAE,OAAO,CAAC;CACnB;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAwDG;AACH,wBAAgB,gBAAgB,CAC5B,OAAO,GAAE,uBAA4B,GACtC,MAAM,CAsOR"}
@@ -0,0 +1,119 @@
1
+ import { exec as x } from "node:child_process";
2
+ import { readFile as A } from "node:fs/promises";
3
+ import S from "node:path";
4
+ import { promisify as M } from "node:util";
5
+ import { normalizePath as p } from "vite";
6
+ const N = M(x);
7
+ function R(i) {
8
+ return i === "" ? "''" : /^[\w@%+=:,./-]+$/.test(i) ? i : "'" + i.replace(/'/g, "'\\''") + "'";
9
+ }
10
+ function D(i = {}) {
11
+ const {
12
+ command: l = "php artisan ts:publish",
13
+ filename: E = "laravel-ts-collected-files.json",
14
+ directory: O = "resources/js/types/data/",
15
+ runOnDevStart: q = !1,
16
+ runOnBuildStart: z = !0,
17
+ reload: F = !0,
18
+ failOnError: h,
19
+ sourceCommand: w,
20
+ onBuildOnlyFunctional: P = !0,
21
+ quiet: y = !0
22
+ } = i, $ = w === !1 ? !1 : w ?? `${l} --source={file}`;
23
+ let r, c;
24
+ const t = /* @__PURE__ */ new Map();
25
+ let u = "", g = !1;
26
+ const d = [], n = "[laravel-ts-publish]", b = async () => {
27
+ t.clear();
28
+ try {
29
+ const e = await A(u, "utf-8"), o = JSON.parse(e);
30
+ for (const f of o) {
31
+ const a = p(S.resolve(r.root, f));
32
+ t.set(a, f);
33
+ }
34
+ } catch (e) {
35
+ if (e instanceof Error && e.code === "ENOENT") {
36
+ r.logger.warn(
37
+ `${n} Manifest not found: ${u}`
38
+ );
39
+ return;
40
+ }
41
+ r.logger.error(
42
+ `${n} Failed to read manifest: ${e instanceof Error ? e.message : String(e)}`
43
+ );
44
+ }
45
+ }, v = () => {
46
+ if (c)
47
+ for (const e of t.keys())
48
+ c.watcher.add(e);
49
+ }, T = () => h !== void 0 ? h : r.command === "build", m = async (e = null, o) => {
50
+ if (g) {
51
+ d.includes(e) || d.push(e);
52
+ return;
53
+ }
54
+ g = !0;
55
+ let a = e && $ ? $.replaceAll(
56
+ "{file}",
57
+ R(e)
58
+ ) : o ?? l;
59
+ y && !a.includes("--quiet") && (a += " --quiet");
60
+ try {
61
+ r.logger.info(`${n} Running: ${a}`, {
62
+ timestamp: !0
63
+ }), await N(a, { cwd: r.root }), r.logger.info(`${n} Types published successfully`, {
64
+ timestamp: !0
65
+ }), F && c && c.ws.send({ type: "full-reload" });
66
+ } catch (s) {
67
+ const C = `${n} Command failed: ${s instanceof Error ? s.message : String(s)}`;
68
+ if (T())
69
+ throw new Error(C, { cause: s });
70
+ r.logger.error(C);
71
+ } finally {
72
+ if (g = !1, d.length > 0) {
73
+ const s = d.shift();
74
+ await m(s);
75
+ }
76
+ }
77
+ };
78
+ return {
79
+ name: "@tolki/vite-plugin-laravel-ts-publish",
80
+ enforce: "pre",
81
+ configResolved(e) {
82
+ r = e, u = p(
83
+ S.resolve(r.root, O, E)
84
+ );
85
+ },
86
+ configureServer(e) {
87
+ c = e;
88
+ },
89
+ async buildStart() {
90
+ if (r.command === "build") {
91
+ if (z) {
92
+ let e = P && !l.includes("--only-functional") ? `${l} --only-functional` : l;
93
+ y && !e.includes("--quiet") && (e += " --quiet"), await m(null, e);
94
+ }
95
+ return;
96
+ }
97
+ await b(), v(), t.size > 0 && r.logger.info(
98
+ `${n} Watching ${t.size} PHP file${t.size === 1 ? "" : "s"} for changes`,
99
+ { timestamp: !0 }
100
+ ), q && await m();
101
+ },
102
+ async handleHotUpdate({ file: e }) {
103
+ const o = p(e);
104
+ if (o === u)
105
+ return r.logger.info(
106
+ `${n} Manifest changed, reloading watched files`,
107
+ { timestamp: !0 }
108
+ ), await b(), v(), [];
109
+ if (t.has(o)) {
110
+ const f = t.get(o) ?? null;
111
+ return await m(f), [];
112
+ }
113
+ }
114
+ };
115
+ }
116
+ export {
117
+ R as escapeShellArg,
118
+ D as laravelTsPublish
119
+ };
package/package.json ADDED
@@ -0,0 +1,86 @@
1
+ {
2
+ "name": "@tolki/ts",
3
+ "version": "0.0.1",
4
+ "description": "A set of TypeScript utilities for the Laravel TypeScript Publish PHP package.",
5
+ "author": "Abraham Arango <https://github.com/abetwothree>",
6
+ "license": "MIT",
7
+ "homepage": "https://tolki.abe.dev/ts/",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/abetwothree/tolki.git",
11
+ "directory": "packages/ts"
12
+ },
13
+ "bugs": {
14
+ "url": "https://github.com/abetwothree/tolki/issues"
15
+ },
16
+ "$schema": "https://raw.githubusercontent.com/vitejs/vite-plugin-registry/refs/heads/main/data/schema/extended-package-json.schema.json",
17
+ "compatiblePackages": {
18
+ "schemaVersion": 1,
19
+ "vite": {
20
+ "type": "compatible",
21
+ "versions": "^7.0.0"
22
+ }
23
+ },
24
+ "main": "dist/index.js",
25
+ "type": "module",
26
+ "keywords": [
27
+ "enum",
28
+ "enums",
29
+ "route",
30
+ "routes",
31
+ "model",
32
+ "models",
33
+ "laravel",
34
+ "utils",
35
+ "utilities",
36
+ "typescript",
37
+ "vite",
38
+ "vite-plugin",
39
+ "tolki"
40
+ ],
41
+ "dependencies": {
42
+ "@tolki/types": "^1.2.0",
43
+ "@tolki/utils": "^1.0.2"
44
+ },
45
+ "peerDependencies": {
46
+ "vite": "^7.0.0"
47
+ },
48
+ "sideEffects": false,
49
+ "files": [
50
+ "dist"
51
+ ],
52
+ "exports": {
53
+ ".": {
54
+ "types": "./dist/index.d.ts",
55
+ "import": "./dist/index.js",
56
+ "require": "./dist/index.js"
57
+ },
58
+ "./enums": {
59
+ "types": "./dist/enums.d.ts",
60
+ "import": "./dist/enums.js",
61
+ "default": "./dist/enums.js"
62
+ },
63
+ "./routes": {
64
+ "types": "./dist/routes.d.ts",
65
+ "import": "./dist/routes.js",
66
+ "default": "./dist/routes.js"
67
+ },
68
+ "./vite": {
69
+ "types": "./dist/vite-plugin.d.ts",
70
+ "import": "./dist/vite-plugin.js",
71
+ "default": "./dist/vite-plugin.js"
72
+ }
73
+ },
74
+ "tolki": {
75
+ "docs": [
76
+ "ts/index.md",
77
+ "ts/enum-utilities-list.md",
78
+ "ts/ts-vite-plugin.md"
79
+ ]
80
+ },
81
+ "scripts": {
82
+ "build": "vite build",
83
+ "readme:build": "ts-node ../../scripts/readme-build.ts --filter @tolki/ts"
84
+ },
85
+ "types": "dist/index.d.ts"
86
+ }