Skip to content

Commit

Permalink
Merge pull request #410 from CloudCannon/feat/last-node-api-fixups
Browse files Browse the repository at this point in the history
Last Node API fixups
  • Loading branch information
bglw authored Sep 7, 2023
2 parents 631c586 + a19d436 commit 5c3f3c3
Show file tree
Hide file tree
Showing 11 changed files with 423 additions and 379 deletions.
714 changes: 359 additions & 355 deletions pagefind/features/node_api/node_base.feature

Large diffs are not rendered by default.

11 changes: 7 additions & 4 deletions pagefind/src/fossick/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -422,11 +422,14 @@ impl Fossicker {

fn build_url(page_url: &Path, relative_to: Option<&Path>, options: &SearchOptions) -> String {
let prefix = relative_to.unwrap_or(&options.site_source);
let trimmed = page_url.strip_prefix(prefix);
let Ok(url) = trimmed else {

let url = if let Ok(trimmed) = page_url.strip_prefix(prefix) {
trimmed
} else if page_url.is_relative() {
page_url
} else {
options.logger.error(format!(
"File was found that does not start with the source directory: {}\nSource: {:?}\nFile: {:?}",
trimmed.err().unwrap(),
"Absolute file was found that does not start with the source directory. Source: {:?}\nFile: {:?}",
prefix,
page_url
));
Expand Down
11 changes: 10 additions & 1 deletion pagefind/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ impl SearchState {
}

pub async fn fossick_many(&mut self, dir: PathBuf, glob: String) -> Result<usize, ()> {
let files = self.walk_for_files(dir, glob).await;
let files = self.walk_for_files(dir.clone(), glob).await;
let log = &self.options.logger;

log.info(format!(
Expand Down Expand Up @@ -322,6 +322,15 @@ impl SearchState {
.into_iter(),
);

// SyntheticFiles should only return the relative path to the file
// _within_ the bundle directory — placing them in a final location
// is left to the API consumer.
for file in files.iter_mut() {
if let Ok(relative_path) = file.filename.strip_prefix(outdir) {
file.filename = relative_path.to_path_buf();
}
}

files
}

Expand Down
6 changes: 3 additions & 3 deletions pagefind/src/service/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -237,13 +237,13 @@ pub async fn run_service() {
}
RequestAction::WriteFiles {
index_id,
bundle_path,
output_path,
} => {
if let Some(index) = get_index(&mut indexes, index_id, err) {
index.build_indexes().await;
let bundle_path = index.write_files(bundle_path.map(Into::into)).await;
let resolved_output_path = index.write_files(output_path.map(Into::into)).await;
send(ResponseAction::WriteFiles {
bundle_path: bundle_path.to_string_lossy().into(),
output_path: resolved_output_path.to_string_lossy().into(),
});
}
}
Expand Down
2 changes: 1 addition & 1 deletion pagefind/src/service/requests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ pub(super) enum RequestAction {
},
WriteFiles {
index_id: u32,
bundle_path: Option<String>,
output_path: Option<String>,
},
GetFiles {
index_id: u32,
Expand Down
2 changes: 1 addition & 1 deletion pagefind/src/service/responses.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ pub(super) enum ResponseAction {
},
BuildIndex {},
WriteFiles {
bundle_path: String,
output_path: String,
},
GetFiles {
files: Vec<SyntheticFileResponse>,
Expand Down
12 changes: 6 additions & 6 deletions wrappers/node/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ await index.getFiles();

// Write the index to disk
await index.writeFiles({
bundlePath: "./public/pagefind"
outputPath: "./public/pagefind"
});
```

Expand Down Expand Up @@ -152,32 +152,32 @@ If successful, the `file` object is returned containing some metadata about the

### index.getFiles

Get buffers of all files in the Pagefind index. Useful for integrating a Pagefind index into the development mode of a static site generator and hosting these files yourself.
Get raw data of all files in the Pagefind index. Useful for integrating a Pagefind index into the development mode of a static site generator and hosting these files yourself.

```js
const { errors, files } = await index.getFiles();

for (const file of files) {
console.log(file.path);
// do something with file.content
// do something with the file.content Uint8Array
}
```

A response with an `errors` array containing error messages indicates that Pagefind failed to action this request.

If successful, `files` will be an array containing file objects. Each object contains a `path` key, which is the URL this file should be served at, and a `content` key containing the raw Buffer of this file.
If successful, `files` will be an array containing file objects. Each object contains a `path` key, which is the URL this file should be served at, and a `content` key containing the raw data as a Uint8Array.

### index.writeFiles

Writes the index files to disk, as they would be written when running the standard Pagefind binary directly.

```js
const { errors } = await index.writeFiles({
bundlePath: "./public/pagefind"
outputPath: "./public/pagefind"
});
```

The `bundlePath` option should contain the path to the desired Pagefind bundle directory. If relative, is relative to the current working directory of your Node process.
The `outputPath` option should contain the path to the desired Pagefind bundle directory. If relative, is relative to the current working directory of your Node process.

A response with an `errors` array containing error messages indicates that Pagefind failed to action this request.

Expand Down
27 changes: 27 additions & 0 deletions wrappers/node/lib/encoding.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
/**
*
* @param {string} b64
* @returns {Uint8Array}
*/
export const decode = (b64) => {
let binString;
if (typeof Buffer !== "undefined" && typeof Buffer.from === "function") {
return Buffer.from(b64, "base64");
} else if (
typeof window !== "undefined" &&
typeof window.atob === "function"
) {
binString = window.atob(b64);
} else if (typeof atob === "function") {
binString = atob(b64);
} else {
throw new Error("Unable to decode base64 data");
}

const size = binString.length;
const bytes = new Uint8Array(size);
for (let i = 0; i < size; i++) {
bytes[i] = binString.charCodeAt(i);
}
return bytes;
};
7 changes: 4 additions & 3 deletions wrappers/node/lib/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { PagefindService } from "./service.js";
import { decode } from "./encoding.js";

/**
* @typedef {import('pagefindInternal').InternalResponseCallback} InternalResponseCallback
Expand Down Expand Up @@ -212,7 +213,7 @@ const writeFiles = (indexId, options) => new Promise((resolve, reject) => {
{
type: action,
index_id: indexId,
bundle_path: options?.bundlePath
output_path: options?.outputPath
}, (response) => {
/** @type {function(InternalResponsePayload): Omit<WriteFilesResponse, 'errors'>?} */
const successCallback = (success) => {
Expand All @@ -222,7 +223,7 @@ const writeFiles = (indexId, options) => new Promise((resolve, reject) => {
}

return {
bundlePath: success.bundle_path
outputPath: success.output_path
}
};
handleApiResponse(resolve, reject, response, successCallback);
Expand Down Expand Up @@ -254,7 +255,7 @@ const getFiles = (indexId) => new Promise((resolve, reject) => {
files: success.files.map(file => {
return {
path: file.path,
content: Buffer.from(file.content, 'base64')
content: decode(file.content)
}
})
}
Expand Down
6 changes: 3 additions & 3 deletions wrappers/node/types/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -162,13 +162,13 @@ export interface WriteOptions {
* If relative, is relative to the cwd.
* @example "./public/pagefind"
*/
bundlePath: string
outputPath: string
}


export interface WriteFilesResponse {
errors: string[],
bundlePath: string
outputPath: string
}

/**
Expand All @@ -183,7 +183,7 @@ export interface GetFilesResponse {

export interface IndexFile {
path: string,
content: Buffer
content: Uint8Array
}

/**
Expand Down
4 changes: 2 additions & 2 deletions wrappers/node/types/internal.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ export interface InternalAddDirRequest {
export interface InternalWriteFilesRequest {
type: 'WriteFiles',
index_id: number,
bundle_path?: string
output_path?: string
}

export interface InternalGetFilesRequest {
Expand Down Expand Up @@ -124,7 +124,7 @@ export interface InternalIndexedDirResponse {

export interface InternalWriteFilesResponse {
type: 'WriteFiles',
bundle_path: string,
output_path: string,
}

export interface InternalGetFilesResponse {
Expand Down

0 comments on commit 5c3f3c3

Please sign in to comment.