@vertesia/memory 0.43.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +421 -0
  3. package/lib/cjs/Builder.js +186 -0
  4. package/lib/cjs/Builder.js.map +1 -0
  5. package/lib/cjs/ContentObject.js +114 -0
  6. package/lib/cjs/ContentObject.js.map +1 -0
  7. package/lib/cjs/ContentSource.js +82 -0
  8. package/lib/cjs/ContentSource.js.map +1 -0
  9. package/lib/cjs/MemoryPack.js +228 -0
  10. package/lib/cjs/MemoryPack.js.map +1 -0
  11. package/lib/cjs/MemoryPackBuilder.js +47 -0
  12. package/lib/cjs/MemoryPackBuilder.js.map +1 -0
  13. package/lib/cjs/commands/copy.js +53 -0
  14. package/lib/cjs/commands/copy.js.map +1 -0
  15. package/lib/cjs/commands/exec.js +82 -0
  16. package/lib/cjs/commands/exec.js.map +1 -0
  17. package/lib/cjs/index.js +28 -0
  18. package/lib/cjs/index.js.map +1 -0
  19. package/lib/cjs/package.json +3 -0
  20. package/lib/cjs/utils/cmdline.js +90 -0
  21. package/lib/cjs/utils/cmdline.js.map +1 -0
  22. package/lib/cjs/utils/rewrite.js +166 -0
  23. package/lib/cjs/utils/rewrite.js.map +1 -0
  24. package/lib/cjs/utils/stream.js +27 -0
  25. package/lib/cjs/utils/stream.js.map +1 -0
  26. package/lib/cjs/utils/tar.js +185 -0
  27. package/lib/cjs/utils/tar.js.map +1 -0
  28. package/lib/esm/Builder.js +178 -0
  29. package/lib/esm/Builder.js.map +1 -0
  30. package/lib/esm/ContentObject.js +103 -0
  31. package/lib/esm/ContentObject.js.map +1 -0
  32. package/lib/esm/ContentSource.js +75 -0
  33. package/lib/esm/ContentSource.js.map +1 -0
  34. package/lib/esm/MemoryPack.js +218 -0
  35. package/lib/esm/MemoryPack.js.map +1 -0
  36. package/lib/esm/MemoryPackBuilder.js +43 -0
  37. package/lib/esm/MemoryPackBuilder.js.map +1 -0
  38. package/lib/esm/commands/copy.js +50 -0
  39. package/lib/esm/commands/copy.js.map +1 -0
  40. package/lib/esm/commands/exec.js +75 -0
  41. package/lib/esm/commands/exec.js.map +1 -0
  42. package/lib/esm/index.js +7 -0
  43. package/lib/esm/index.js.map +1 -0
  44. package/lib/esm/utils/cmdline.js +86 -0
  45. package/lib/esm/utils/cmdline.js.map +1 -0
  46. package/lib/esm/utils/rewrite.js +161 -0
  47. package/lib/esm/utils/rewrite.js.map +1 -0
  48. package/lib/esm/utils/stream.js +23 -0
  49. package/lib/esm/utils/stream.js.map +1 -0
  50. package/lib/esm/utils/tar.js +175 -0
  51. package/lib/esm/utils/tar.js.map +1 -0
  52. package/lib/tsconfig.tsbuildinfo +1 -0
  53. package/lib/types/Builder.d.ts +72 -0
  54. package/lib/types/Builder.d.ts.map +1 -0
  55. package/lib/types/ContentObject.d.ts +43 -0
  56. package/lib/types/ContentObject.d.ts.map +1 -0
  57. package/lib/types/ContentSource.d.ts +32 -0
  58. package/lib/types/ContentSource.d.ts.map +1 -0
  59. package/lib/types/MemoryPack.d.ts +46 -0
  60. package/lib/types/MemoryPack.d.ts.map +1 -0
  61. package/lib/types/MemoryPackBuilder.d.ts +18 -0
  62. package/lib/types/MemoryPackBuilder.d.ts.map +1 -0
  63. package/lib/types/commands/copy.d.ts +8 -0
  64. package/lib/types/commands/copy.d.ts.map +1 -0
  65. package/lib/types/commands/exec.d.ts +7 -0
  66. package/lib/types/commands/exec.d.ts.map +1 -0
  67. package/lib/types/index.d.ts +14 -0
  68. package/lib/types/index.d.ts.map +1 -0
  69. package/lib/types/utils/cmdline.d.ts +10 -0
  70. package/lib/types/utils/cmdline.d.ts.map +1 -0
  71. package/lib/types/utils/rewrite.d.ts +38 -0
  72. package/lib/types/utils/rewrite.d.ts.map +1 -0
  73. package/lib/types/utils/stream.d.ts +9 -0
  74. package/lib/types/utils/stream.d.ts.map +1 -0
  75. package/lib/types/utils/tar.d.ts +40 -0
  76. package/lib/types/utils/tar.d.ts.map +1 -0
  77. package/package.json +40 -0
  78. package/src/Builder.ts +239 -0
  79. package/src/ContentObject.ts +114 -0
  80. package/src/ContentSource.ts +88 -0
  81. package/src/MemoryPack.ts +233 -0
  82. package/src/MemoryPackBuilder.ts +55 -0
  83. package/src/builder.test.ts +214 -0
  84. package/src/commands/copy.ts +53 -0
  85. package/src/commands/exec.test.ts +22 -0
  86. package/src/commands/exec.ts +83 -0
  87. package/src/index.ts +14 -0
  88. package/src/utils/cmdline.test.ts +32 -0
  89. package/src/utils/cmdline.ts +92 -0
  90. package/src/utils/rewrite.test.ts +65 -0
  91. package/src/utils/rewrite.ts +167 -0
  92. package/src/utils/stream.test.ts +13 -0
  93. package/src/utils/stream.ts +27 -0
  94. package/src/utils/tar.test.ts +48 -0
  95. package/src/utils/tar.ts +203 -0
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,421 @@
1
+ # Memory Pack
2
+
3
+ This is the core of the Composable memory Pack library.
4
+ It defines the memory pack commands and provide an API to build and read memory packs.
5
+
6
+ A memory pack is an indexed tar file containing a `metadata.json` and other random files (images, documents, text files etc.). The `metadata.json` file is defining the properties of a memory pack. The metadata is used to describe the memory and the other files in the tar can be used to hold the additional content you need in order to create a context for the interaction with a target LLM.
7
+
8
+ To build a memory pack you must use the memory pack API or the `memo` application provided by `@vertesia/memory-cli` package. The tar contains a special file named `.index` which is used to index the tar content so that the tar entries can be quickly extracted from the tar without nneeding to untar the entire content.
9
+
10
+ ## Memory Pack Recipe
11
+
12
+ A recipe is a typescript file that is used to build a memory pack.
13
+ The recipe can contain any javascript code but it must use the builtin commands to create the memory TAR file.
14
+
15
+ A memory tpack recipe has the following structure:
16
+
17
+ ```js
18
+ import { copy, ... other commands ... } from "@vertesia/memory-commands";
19
+
20
+ // You can optionally extend an existing memory pack
21
+ await from("path/to/memory.tar")
22
+
23
+ /** then you can build the memory tar content using builtin commands
24
+ * You can either use the bult-in commands or `exec` to run a shell command
25
+ */
26
+
27
+ // ... Your commands here ...
28
+
29
+ /**
30
+ * At the end of the file you must export the memory pack metadata.
31
+ * This is a JSON object which holds the properties to be used when creating LLM interactions.
32
+ */
33
+ export default {
34
+ someProperty: "hello",
35
+ ...
36
+ }
37
+ ```
38
+
39
+ ## Memory Pack Commands.
40
+
41
+ The only dependency you need to import in your recipe ts file is the `@becmposable/memory-commands` package. This package contains all the buil-in commands which are grouped in two categories: execution commands and content loading commands:
42
+
43
+ ### Context commands
44
+ 1. **vars** - Get the build user variables
45
+ 2. **tmpdir** - Get or create a temporary directory for use while building
46
+ 3. **getBuilder** - Get the builder instance.
47
+
48
+ ### Execution commands
49
+ 1. **from** - Extends an existing memory pack (a tar file)
50
+ 2. **exec** - Execute a shell command.
51
+ 3. **copy** - Copy a file to the tar. The file content can be transformed using the built-in transformers. See the [copy command](#copy) for more details.
52
+ 4. **copyText** - Copy an inline text or string variable as a tar entry.
53
+ 5. **build** - Build an external recipe.
54
+
55
+ ### Content loading commands
56
+
57
+ These commands can be used to fetch content from files. The result is returned as a variable which will only fetch the content when used. All these commands supports globs as argument to fretch content from multiple files. When a glob is used the result will alwaysbe an array of variables.
58
+ 1. **content** - fetch the text content from a text file.
59
+ 2. **json** - fetch a JSON object from a json file.
60
+ 3. **pdf** - extract the text content from a PDF file.
61
+ 4. **docx** - extract the text content from a Docx file.
62
+ 5. **media** - Load an image with an optional conversion. The image is exported as base64 text, when the variable is referenced in the exported memory metadata.
63
+
64
+ #### vars
65
+
66
+ **Signature:** `vars (): Record<string,any>`
67
+
68
+ A command that returns the user variables which were specified when invoking the memory pack build.
69
+ These variables can be used to parametrize the recipe. When using the `memo` cli application (i.e. `@vertesia/memory-cli`) you can pass vars to the recipe by using command line parameters which starts with a `--var-` prefix.
70
+
71
+ **Example:** `--var-language fr` will produce a property `language` whith a value of `'fr'`.
72
+
73
+ **Usage:**
74
+ ```js
75
+ import { vars } from "@vertesia/memory-commands"
76
+
77
+ const { language } = vars();
78
+ ```
79
+
80
+ #### tmpdir
81
+
82
+ **Signature:** `tmpdir (): string`
83
+
84
+ Get or create a temporary directory. If the directory was not yet created it will be created and its path returned.
85
+
86
+ If created, the temporary directory will be automatically removed at the end of the build.
87
+
88
+ **Usage:**
89
+
90
+ ```js
91
+ import { tmpdir } from "@vertesia/memory-commands";
92
+
93
+ const wd = tmpdir();
94
+
95
+ await exec(`ls -al > ${wd}/text.txt`);
96
+ ```
97
+
98
+ ### getBuilder
99
+
100
+ **Signature:** `getBuilder (): Builder`
101
+
102
+ Get the instance of the builder which is used to build the current recipe ts file.
103
+
104
+
105
+ ### from
106
+
107
+ **Signature:** `from (location: string, options?: FromOptions): void`
108
+
109
+ The from command load an existing memory pack tar as a source of the current pack being built. You can filter which files and metadata properties will be included from the soruce tar by specifying a `files` filter and a metadata properties `projection`.
110
+
111
+ The `from` command is an asynchronous operation so you need to `await` for its completion.
112
+
113
+ The shape of the `FromOptions` is:
114
+
115
+ ```ts
116
+ {
117
+ files?: string[];
118
+ projection?: Record<string, boolean | 0 | 1>;
119
+ }
120
+ ```
121
+ The `files` filter is an array of globs as supported by the [micromatch](https://www.npmjs.com/package/micromatch) library. You can either include files using globs expressions or fiels by prepending the glob expression with an `!` character.
122
+
123
+ The `projection` is an object which map keys to a truthy or falsy value. You can either use false or true to exclude or include properties not both.
124
+
125
+ *Example:*
126
+
127
+ ```js
128
+ import { vars, from } from "@vertesia/memory-commands"
129
+ await from("./memory-source.tar", {
130
+ files: ["images/*.png"],
131
+ projection: {
132
+ name: true,
133
+ language: true,
134
+ }
135
+ })
136
+ // export a new metadata object
137
+ export default {
138
+ theme: vars.theme || 'dark'
139
+ }
140
+ ```
141
+
142
+ The memory pack built above will contain all the `images/*.png` files from the source tar and the metadata JSON object will contain the `name` and `language` properties from the source memory pack metadata and will add a new metadata property named `theme`.
143
+
144
+
145
+ ### exec
146
+
147
+ **Signature:** `exec (cmd: string, options?: ExecOptions): Promise<void | string>`
148
+
149
+ Execute a shell command. You can execute a pipe of shell commands or use stdout redirection at the end of the command:
150
+
151
+ The `exec` command is asynchronous so you need to use await when incoking it. If no output redirection is specified then the output will be returned as a string from the `exec()` function
152
+
153
+ **Example:**
154
+
155
+ ```javascript
156
+ import { tmpdir, exec } from "@vertesia/memory-commands"
157
+ const wd = tmpdir();
158
+ const output = await exec("cat some/file | wc -l")
159
+ await exec(`cat some/file | wc -l > ${wd}out.txt`)
160
+ ```
161
+
162
+ ### copy
163
+
164
+ **Signature:** `copy (location: SourceSpec, path: string, options?: CopyOptions): void`
165
+
166
+ This command will copy the content of a file to a tar entry specified by the `path` argument.
167
+ The `location` argument specify from source from where the content is copied.
168
+ It may be either a `string` or a `ContentSource` object. ContentSource objects are returned by any of the [Content Loading Commands](#content-loading-commands).
169
+
170
+ If location is a string it will be expected to point to a file path or to a glob expression.
171
+ If a glob expression is used the the `copy` operation will copy the content of all the matching files. You can, in that case, specify a path rewrite expression as the `path` argument.
172
+
173
+ Youn can transform the file content when copying it to the tar by using the `options` argument. The shape of the options is:
174
+
175
+ ```ts
176
+ export interface CopyOptions {
177
+ media?: {
178
+ max_hw?: number;
179
+ format?: "jpeg" | "png";
180
+ };
181
+ extractText?: boolean | string;
182
+ }
183
+ ```
184
+
185
+ You can convert images by specfying a max height or widtth and / or an output image format. For documents like pdf or docx you can specify `extractText: "pdf" | "docx" | boolean`. If true is specified the type of text extraction will be guessed from the file extension.
186
+
187
+ **Example:**
188
+
189
+ ```js
190
+ import { exec, copy, tmpdir } from "@vertesia/memory-commands"
191
+ const wd = tmpdir();
192
+ await exec(`cat some/file > ${wd}/out.txt`)
193
+ copy(`${wd}/out.txt`, 'out.txt');
194
+ copy('./my-project/src/**/*.ts', './my-project/src!sources/*')
195
+ ```
196
+
197
+ The rewrite expression in the example above `./my-project/src!sources/*` means: strip the prefix `./my-project/src` fromt he copied file and prefix the remaining od the path with the value `sources/`.
198
+
199
+ #### Path rewrite expressions
200
+
201
+ A path rewrite expression is composed of two parts:
202
+ 1. an optional prefix separated by a `!` charcater from the rest of the path. If present this prefix will be removed from the matched path.
203
+ If no prefix is specified then the entrie directory part of the matched path will be removed.
204
+ 2. A mandatory suffix which is describing how to rewrite the matched path. The suffix may contain either a wildcard `*` which will be replaced with the matched path (without the removed prefix), either a combination of the followinf variables:
205
+ * `%n` - the file name without the extension
206
+ * `%e` - the extension
207
+ * `%f` - the file name including the extension
208
+ * `%d` - the directory path (not including the removed prefix)
209
+ * `%i` - the 0 based index of the file in the matched array of files.
210
+
211
+ **Examples:**
212
+
213
+ ```js
214
+ // copy all .ts files flatened in the sources directory (the directory structure is not preserved)
215
+ copy("work/docs/project1/src/**/*.ts", "sources/*")
216
+ // copy all .ts files in the sources directory and recreate the subdirectories structure inside src/
217
+ copy("work/docs/project1/src/**/*.ts", "work/docs/project1/src!sources/*")
218
+ // Remove the work/ prefix and preserver the same subdirectories structure including images/
219
+ // and replace the file extension with .png
220
+ copy("work/images/**/*.png", "work!%d/%n.jpeg")
221
+ // Copy all images inaide a images/ folder without preserving subdirectories and append the index of the image
222
+ copy("work/images/**/*.png", "images/%n-%i.%e")
223
+ ```
224
+
225
+ In the last example for the mnatched files: `work/images/header/home.png` and `work/images/footer/logo.png` the result will be: `images/home-0.png`, `images/logo-1.png`
226
+
227
+ ### copyText
228
+
229
+ **Signature:** `copyText (text: string, path: string): void`
230
+
231
+ This command will create a new entry in the target memory pack tar using the content you specified through the `text` argument. The tar entry path is specified by the `path` argument.
232
+
233
+ ```js
234
+ import { exec, copyText } from "@vertesia/memory-commands"
235
+ const content = await exec(`cat some/file`)
236
+ copyText(content.trim(), 'content.txt')
237
+ ```
238
+
239
+ ### build
240
+
241
+ **Signature:** `build (recipePath: string, options?: BuildOptions): void`
242
+
243
+ Build a memory pack from a recipe file. You can use this command if you need to build multiple memory packs.
244
+
245
+ The `BuildOptions` options have the following shape:
246
+
247
+ ```ts
248
+ export interface BuildOptions {
249
+ indent?: number;
250
+ /**
251
+ * the path to save the output. Defaults to 'memory.tar'.
252
+ * If no .tar extension is present it will be added
253
+ */
254
+ out?: string;
255
+
256
+ /**
257
+ * If set, suppress logs. Defaults to false.
258
+ */
259
+ quiet?: boolean;
260
+
261
+ /**
262
+ * If true, compress the output (tar or json) with gzip. Defaults to false.
263
+ */
264
+ gzip?: boolean;
265
+
266
+ /**
267
+ * Vars to be injected into the script context as the vars object
268
+ */
269
+ vars?: Record<string, any>;
270
+
271
+ /**
272
+ * Optional publish action
273
+ * @param file
274
+ * @returns the URI of the published memory
275
+ */
276
+ publish?: (file: string, name: string) => Promise<string>
277
+ }
278
+ ```
279
+
280
+ **Usage:**
281
+
282
+ ```js
283
+ import { build, tmpdir } from "@vertesia/memory-commands";
284
+ const wd = tmpdir();
285
+ await build("./some/recipe.ts", { out: `${wd}}/child-memory`});
286
+ ```
287
+
288
+ ### content
289
+
290
+ **Signature:** `content (location: string, encoding?: BufferEncoding): ContentObject | ContentObject[]`
291
+
292
+ If the location is a glob expression then an arry of `ContentObject` is returned. A `ContentObject` implements `ContentSource` so it can be used as the location argument of the copy operation.
293
+ The actual cotnent of a file is only fetched (and trasformed) only when the ContentObject is used: either a method of the object is used, either it is assigned to a value of a metadata property.
294
+
295
+ The `content` command simply load the content of the given file(s) as a text using an optional encoding. The default encoding is "utf-8".
296
+
297
+ ### json
298
+
299
+ **Signature:** `json (location: string) => ContentObject | ContentObject[]`
300
+
301
+ Load a JSON object from a json file. When assigned as a metadata property the content will by transformed in a JSON object.
302
+
303
+ ### pdf
304
+
305
+ **Signature:** `pdf (location: string) => PdfObject | PdfObject[]`
306
+
307
+ Load a PdfObject form a pdf file. When assigned as a metadata property the PdfObject is transformed to the text representation of the PDF.
308
+
309
+ **Example:**
310
+
311
+ ```js
312
+ import { pdf } from "@vertesia/memory-commands";
313
+
314
+ const doc = pdf("./my-doc.pdf")
315
+
316
+ export default {
317
+ textContent: doc
318
+ }
319
+ ```
320
+
321
+ In the example above the PDF text will be extracted from the pdf and ibjected as the textContent property ion the memory pack metadata.
322
+
323
+ ### docx
324
+
325
+ Load a DocxObject form a docx file. When assigned as a metadata property the DocxObject is transformed to the text representation of the Docx.
326
+
327
+ **Signature:** `docx (location: string) => DocxObject | DocxObject[]`
328
+
329
+ ### media
330
+
331
+ **Signature:** `json (location: string, options?: MediaOptions) => MediaObject | MediaObject[]`
332
+
333
+
334
+ Load a MediaObject form a docx file. When assigned as a metadata property the MediaObject is transformed to text representation of the image which is the base64 encoded image.
335
+
336
+ The media command accepts an additional argument which has the shape:
337
+
338
+ ```
339
+ export interface MediaOptions {
340
+ max_hw?: number;
341
+ format?: "jpeg" | "png";
342
+ }
343
+ ```
344
+
345
+ You can thus convert the image before using it.
346
+
347
+ **Example:**
348
+
349
+ ```js
350
+ import { pdf } from "@vertesia/memory-commands";
351
+
352
+ const images = media("./images/*.jpeg")
353
+
354
+ export default {
355
+ images: images
356
+ }
357
+ ```
358
+
359
+ In the example above the an array of images encoded as base64 will be injected in the `images` property pf the memory pack metadata.
360
+
361
+
362
+ ### Custom commands
363
+
364
+ To create custom commands you have 2 options. Either you write the command in as a command line application and invoke it through the `exec` command, either you write a javascript function, package it in an external library and the import it in the recipe ts file.
365
+
366
+ Here is a template of custom command functions:
367
+
368
+ ```js
369
+ import { getBuilder } from "@vertesia/memory-commands";
370
+ import fs from "node:fs";
371
+
372
+ export myCommand(message:string) {
373
+ const wd = builder.tmpdir();
374
+ // this is the current instance of the builder being used to build the memory pack.
375
+ const builder = getBuilder();
376
+ // you can add a variable in the build vars:
377
+ builder.vars.greeting = 'hello world!';
378
+ // or write a file named greeting.txt in the current build tmpdir
379
+ fs.writeFileSync(`${wd}/greeting.txt`, "hello world!", "utf-8");
380
+ // or create a tar entry named greeting.txt
381
+ builder.copyText("hello world!", "greeting.txt");
382
+ // refer to Builder API for other operations.
383
+ }
384
+ ```
385
+
386
+ ## Examples
387
+
388
+ ### Release Highlights
389
+
390
+ This example builds a memory pack with the information on which issues were fixed between to commit SHA.
391
+
392
+ ```js
393
+ import { copy, copyText, exec, tmpdir, vars } from "@vertesia/memory-commands";
394
+
395
+ const { start, end } = vars();
396
+ if (!start || !end) {
397
+ console.error("Please provide start and end tags using --var-start and --var-end");
398
+ process.exit(1);
399
+ }
400
+
401
+ const wd = tmpdir();
402
+
403
+ console.log(`Retrieving issues between ${start}and ${end}...`)
404
+ // Get list of commit logs containing '#' between the two tags and extract unique issue numbers
405
+ const issue_numbers = await exec(`git log ${start}..${end} --oneline | grep -o '#[0-9]\\+' | sed 's/#//' | sort -u`) as string;
406
+
407
+ for (const issue of issue_numbers.trim().split("\n")) {
408
+ console.log(`Processing issue #${issue}`)
409
+ const issue_content = await exec(`gh issue view ${issue}`) as string;
410
+ copyText(issue_content, `issues/${issue}.txt`);
411
+ }
412
+
413
+ console.log("Generating diff");
414
+ await exec(`git diff --submodule=diff ${start}...${end} > ${wd}/range_diff.txt`)
415
+ copy(`${wd}/range_diff.txt`, "range_diff.txt");
416
+
417
+ export default {
418
+ from_version: start,
419
+ release_version: end,
420
+ }
421
+ ```